위의 이미지를 기준으로 설명하면 아래와 같다.
1. Target: 새로운 인터페이스 규격(클라이언트가 사용하며 구체 클래스에 의존하지 않는다)
2. Adaptee: 기존의 코드
3. Adapter: 기존의 코드를 새로운 인터페이스 규격에 맞추기 위한 클래스
어댑터 패턴은 프린터기 예제가 가장 이해하기 쉽기 때문에 여기에서는 프린터기를 예로 코드를 작성한다.
public class Lg {
private String text;
public Lg(String text) {
this.text = text;
}
public String printColorText() {
return text;
}
}
public class Samsung {
private String data;
private String color;
public Samsung(String data, String color) {
this.data = data;
this.color = color;
}
public String printColorText() {
return "[" + color + "]:" + data;
}
public String getData() {
return data;
}
}
public interface Printer {
String printColor();
String printGrey();
}
public class LgAdapter implements Printer {
private Lg lg;
public LgAdapter(Lg lg) {
this.lg = lg;
}
@Override
public String printColor() {
return "[검정]: " + lg.printColorText();
}
@Override
public String printGrey() {
return "[흑백]: " + lg.printColorText();
}
}
public class SamsungAdapter implements Printer {
private Samsung samsung;
public SamsungAdapter(Samsung samsung) {
this.samsung = samsung;
}
@Override
public String printColor() {
return samsung.printColorText();
}
@Override
public String printGrey() {
return "[흑백]: " + samsung.getData();
}
}
기존의 클래스를 어댑터에서 새로운 규격게 맞게 사용할 수 있게 만들어 둔 덕분에 컴퓨터는 프린터의 제조사에 상관 없이 아무 프린터기나 사용할 수 있다.
public class Computer {
private Printer printer;
public Computer(Printer printer) {
this.printer = printer;
}
public void usePrinter() {
String colorText = printer.printColor();
System.out.println("colorText = " + colorText);
String greyText = printer.printGrey();
System.out.println("greyText = " + greyText);
}
public static void main(String[] args) {
Lg lg = new Lg("보고서");
LgAdapter lgAdapter = new LgAdapter(lg);
Samsung samsung = new Samsung("긴급 메시지", "적색");
SamsungAdapter samsungAdapter = new SamsungAdapter(samsung);
Computer window1 = new Computer(lgAdapter);
window1.usePrinter();
Compter window2 = new Computer(samsungAdapter);
window2.usePrinter();
}
}