어댑터 패턴

ynkim·2024년 12월 12일
0

어댑터

호환되지 않는 인터페이스를 가진 객체들이 협업할 수 있도록 하는 구조적 디자인 패턴

구조

오브젝트 어댑터

  • 어댑터가 한 객체의 인터페이스를 구현하고 다른 객체는 래핑한다.
  • 클라이언트 인터페이스: 다른 클래스들이 클라이언트 코드와 공동 작업할 수 있도록 따라야하는 프로토콜
  • 서비스: 호환되지 않는 인터페이스를 가져 클라이언트가 직접 사용할 수 없는 클래스
  • 어댑터: 클라이언트와 서비스 양쪽에서 작동할 수 있는 클래스로 클라이언트 인터페이스를 구현하고 서비스 객체를 래핑한다.

클래스 어댑터

  • 어댑터가 동시에 두 객체의 인터페이스를 상속한다.

예시 코드

public class RoundHole {
    private double radius;

    public RoundHole(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public boolean fits(RoundPeg peg) {
        boolean result;
        result = (this.getRadius() >= peg.getRadius());
        return result;
    }
}

public class RoundPeg {
    private double radius;

    public RoundPeg() {}

    public RoundPeg(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }
}

public class SquarePeg {
    private double width;

    public SquarePeg(double width) {
        this.width = width;
    }

    public double getWidth() {
        return width;
    }

    public double getSquare() {
        double result;
        result = Math.pow(this.width, 2);
        return result;
    }
}

public class SquarePegAdapter extends RoundPeg {
    private SquarePeg peg;

    public SquarePegAdapter(SquarePeg peg) {
        this.peg = peg;
    }

    @Override
    public double getRadius() {
        double result;
        result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
        return result;
    }
}

public class Demo {
    public static void main(String[] args) {
        RoundHole hole = new RoundHole(5);
        RoundPeg rpeg = new RoundPeg(5);
        if (hole.fits(rpeg)) {
            System.out.println("Round peg r5 fits round hole r5.");
        }

        SquarePeg smallSqPeg = new SquarePeg(2);
        SquarePeg largeSqPeg = new SquarePeg(20);

        SquarePegAdapter smallSqPegAdapter = new SquarePegAdapter(smallSqPeg);
        SquarePegAdapter largeSqPegAdapter = new SquarePegAdapter(largeSqPeg);
        if (hole.fits(smallSqPegAdapter)) {
            System.out.println("Square peg w2 fits round hole r5.");
        }
        if (!hole.fits(largeSqPegAdapter)) {
            System.out.println("Square peg w20 does not fit into round hole r5.");
        }
    }
}
  • 호환되지 않는 인터페이스가 있는 클래스가 두개 이상인지 확인
  • 클라이언트 인터페이스를 선언
  • 어댑터 클래스를 생성 후 클라이언트 인터페이스를 구현
  • 어댑터 클래스에 필드를 추가하여 서비스 객체를 참조 (생성자를 통해서도 가능)
  • 어댑터는 데이터 형식 변환만 처리해야 함
  • 클라이언트는 클라이언트 인터페이스를 통해 어댑터를 사용

장단점

장점

  • 단일 책임 원칙: 비즈니스 로직에서 데이터 변환 코드를 분리 가능
  • 개방/폐쇄 원칙: 클라이언트 인터페이스를 통해 어댑터를 사용

단점

  • 클래스 개수 증가 혹은 코드의 복잡성

0개의 댓글