# 어댑터 (Adapter) 패턴

# 어댑터 패턴이란 무엇인가요?

한 클래스의 인터페이스를 클라이언트에서 사용하고자하는 다른 인터페이스로 변환하는 것입니다.
한국의 콘센트는 220v이기 때문에 110v가 필요한 일본제품을 사용할 때 중간에 어댑터를 끼어넣는 것처럼, 어댑터 패턴도 인터페이스 호환성 문제 때문에 같이 쓸 수 없는 클래스들을 중간에서 연결시켜주는 역할을 합니다.

  • UML 어댑터 uml

# 예시 코드

  • 호환되는 기존 객체 (Target => Moveable)
public interface Moveable {
    public void madeby();
    public void weight();
}
public class Notebook implements Moveable {
    @Override
    public void madeby() {
        System.out.println("Japan");
    }
    @Override
    public void weight() {
        System.out.println("1kg");
    }
}
  • 호환이 되지 않는 다른 객체 (Adaptee => Computer)
public interface Stationary {
    public void madeby();
    public void size();
}
public class Computer implements Stationary {
    @Override
    public void madeby() {
        System.out.println("Korea");
    }
    @Override
    public void size() {
        System.out.println("big size");
    }
}

Notebook객체대신 Computer객체를 사용해야 되는 상황이 왔다고 가정하면, 인터페이스 때문에 Computer 객체를 바로 사용할 수 없다. 이때, 어댑터를 만들어준다.
-- 어댑터 (Adapter => ComputerAdapter)

public class ComputerAdapter implements Moveable{
    Computer computer;
    
    public ComputerAdapter(Computer computer) {
        this.computer = computer;
    }
    @Override
    public void madeby() {
        computer.madeby();
    }
    @Override
    public void weight() {
        computer.size();  //연결하고 싶은 메소드를 사용함
    }
}

-- 어댑터 사용

public class Test {
    public static void main(String[] args) {
        Computer computer = new Computer();
        Moveable computerAdapter = new ComputerAdapter(computer);
        
        Notebook notebook = new Notebook();
        
        moveableThing(computerAdapter);
        moveableThing(notebook);
    }
    public static void moveableThing(Moveable moveable){
        moveable.madeby();
        moveable.weight();
    }
}

# 어댑터 패턴은 언제 사용하나요?

  • 라이브러리가 외부라이브러리거나 이미 많이 사용해서 인터페이스를 바꾸고 싶어도 쉽게 바꿀 수 없는 경우에 사용합니다.
  • 두 클래스가 유사한 작업을 수행하지만, 다른 인터페이스를 가질 경우에 사용합니다.

# 어댑터 패턴의 장점은 무엇인가요?

  • 기존 코드를 변경하지 않고 원하는 인터페이스 구현체를 만들어서 재사용을 할 수 있습니다.(OCP- 개방폐쇠원칙)
  • 기존 코드가 하던 일과 특정 인터페이스 구현체로 변환하는 작업을 다른 클래스로 분리하여 관리할 수 있습니다.(SRP- 단일책임원칙)

# 어댑터 패턴의 단점은 무엇인가요?

  • 새 클래스가 생겨 복잡도가 증가하기도 합니다.

# 실제로 사용한 어댑터를 사용한 예는 무엇인가요?

  • 자바의 Arrays와 Collections
  • 스프링 Security, 스프링MVC의 HandlerAdapter

# 참고자료

출처: https://jusungpark.tistory.com/22 [정리정리정리]
출처: https://kingchan223.tistory.com/296?category=894627 [어제보다 오늘 더]