JAVA/DesignPattern

Design Pattern 디자인패턴 Adapter Pattern 어답터 패턴

호두밥 2021. 12. 16. 00:25

Adapter Pattern 어답터 패턴

어답터 패턴은 서로 다른 인터페이스를 바꿔치기 할 수 있도록 해주는 패턴입니다. 예를 들어 5핀 충전기에 어답터를 끼우면 C type 기기를 충전할 수 있는 것과 같은 원리입니다. 

Adapter Pattern 어답터 패턴의 장단점

장점

  • 비즈니스 로직에서 인터페이스 및 데이터 변환 로직을 분리할 수 있습니다. (단일책임원칙)
  • 기존 클래스 코드를 변경하지 않고도 새로운 이터 형태로 변환할 수 있습니다. (개방폐쇄원칙)

단점

  • 코드의 복잡성이 증가할 수 있습니다. (새로운 클래스가 생성될 경우, 어답터와 인터페이스를 함께 도입해야 하기 때문에 때로는 클래스 자체를 변경하는 것이 더 간단할 수도 있습니다.) 

Adapter Pattern 어답터 패턴 구현

어답터 클래스는 인퍼페이스 5핀 충전기를 C type 인터페이스로 사용할 수 있도록 변환해줍니다. 즉 Adapter 클래스 자체가 C type의 구현체가 됩니다. 그리고 내부 구성요소로 Micro 5 pin을 갖고 있으면서 생성자를 통해 외부에서 Micro 5 5 pin 객체를 받아서 사용합니다.   

public class Adapter implements Ctype{

    private Micro5pin micro5pin;

    public Adapter( Micro5pin micro5pin ) {
        this.micro5pin = micro5pin;
    }


    @Override
    public String charging() {
        return micro5pin.charging();
    }
}
public interface Ctype {
    public String charging();
}
public class CtypeCableA implements Ctype {
    @Override
    public String charging() {
        return "C type Cable A is charging";
    }
}
public interface Micro5pin {
    public String charging();
}
public class Micro5pinCableB implements Micro5pin{
    @Override
    public String charging() {
        return "Micro 5 pin Cable B is charging";
    }
}

 

public class Main {

    public static void main(String[] args) {

		// 5핀 케이블을 생성합니다.
        Micro5pin cable = new Micro5pinCableB();
        System.out.println(cable.charging());

		// 어답터를 이용해 Ctype으로 변환해줍니다.
        Ctype adapter = new Adapter(cable);
        System.out.println(adapter.charging());

    }
}

 Ctype으로 변환했지만, Micro 5 pin의 기능을 그대로 사용하고 있는 것을 확인할 수 있습니다. 

Micro 5 pin Cable B is charging
Micro 5 pin Cable B is charging

 

참조