Adapter Pattern은 구조 패턴으로 인터페이스나 구현을 복합하는 것이 아닌, 객체를 합성하는 방법을 제공한다. 이는 컴파일 단계에서가 아닌 런타임 단계에서 복합 방법이나, 대상을 변경할 수 있다는 점에서 유연성을 가진다.
public class Volt {
private int volts;
public Volt(int v){
this.volts=v;
}
public int getVolts() {
return volts;
}
public void setVolts(int volts) {
this.volts = volts;
}
}
public class Socket {
public Volt getVolt(){
return new Volt(120);
}
}
public interface SocketAdapter {
public Volt get120Volt();
public Volt get12Volt();
public Volt get3Volt();
}
public class SocketClassAdapterImpl extends Socket implements SocketAdapter{
@Override
public Volt get120Volt() {
return getVolt();
}
@Override
public Volt get12Volt() {
Volt v= getVolt();
return convertVolt(v,10);
}
@Override
public Volt get3Volt() {
Volt v= getVolt();
return convertVolt(v,40);
}
private Volt convertVolt(Volt v, int i) {
return new Volt(v.getVolts()/i);
}
}
public class SocketObjectAdapterImpl implements SocketAdapter{
//Using Composition for adapter pattern
private Socket sock = new Socket();
@Override
public Volt get120Volt() {
return sock.getVolt();
}
@Override
public Volt get12Volt() {
Volt v= sock.getVolt();
return convertVolt(v,10);
}
@Override
public Volt get3Volt() {
Volt v= sock.getVolt();
return convertVolt(v,40);
}
private Volt convertVolt(Volt v, int i) {
return new Volt(v.getVolts()/i);
}
}
public static void main(String[] args) {
// object adapter
SocketAdapter sockAdapter = new SocketObjectAdapterImpl();
Volt v3 = sockAdapter.get3Volt();
Volt v12 = sockAdapter.get12Volt();
Volt v120 = sockAdapter.get120Volt();
// class adapter
SocketAdapter sockAdapter = new SocketClassAdapterImpl();
Volt v3 = sockAdapter.get3Volt();
Volt v12 = sockAdapter.get12Volt();
Volt v120 = sockAdapter.get120Volt();
}