어댑터 패턴

이진호·2022년 9월 26일
0

GoF 디자인 패턴

목록 보기
1/3
post-thumbnail

어댑터 패턴(Adapter Pattern)

어댑터 패턴(Adapter Pattern)은 특정 클래스 인터페이스를 클라이언트에서 요구하는 다른 인터페이스로 변환합니다. 인터페이스가 호환되지 않아 같이 쓸 수 없었던 클래스를 사용할 수 있게 도와줍니다.

  • 어댑티를 새로 바뀐 인터페이스로 감쌀 때는 객체 구성(composition)을 사용. 이에 따라 어댑티의 모든 서브클래스에 어댑터를 적용 가능.
  • 클라이언트를 특정 구현이 아닌 인터페이스에 연결.

클래스 어댑터

  • 클래스 어댑터를 쓰려면 다중 상속이 필요(자바는 불가).

예제

// 구형 인터페이스 Enumeration을 신형 인터페이스 Iterator로 연결
public class EnumerationIterator implements Iterator<Object> {
    // 어댑티를 인스턴스 변수에 저장(객체 컴포지션)
    private Enumeration<?> enumeration; 

    public EnumerationIterator(Enumeration<?> enumeration) {
        this.enumeration = enumeration;
    }

    @Override
    public boolean hasNext() {
        // Iterator의 hasNext() 메소드를 Enumeration의 hasMoreElements() 메서드로 연결
        return this.enumeration.hasMoreElements();
    }

    @Override
    public Object next() {
        // Iterator의 next() 메소드를 Enumeration의 nextElement() 메서드로 연결
        return this.enumeration.nextElement();
    }

    @Override
    public void remove() {
        // Iterator의 remove() 메소드는 지원되지 않으므로 예외처리
        throw new UnsupportedOperationException();
    }
}

출처

0개의 댓글