어댑터 패턴 (Adapter Parttern)

구교석·2024년 3월 18일
post-thumbnail

어댑터 패턴 (Adapter Parttern)은 구조 패턴 중 하나로 이는 소프트웨어에서 특정한 문제를 해결하기 위해 반복적으로 발생하는 구조를 식별하고, 그 구조에 따라 일반화된 해결책을 제시하는 것을 의미합니다.

어댑터 패턴이란?

두 개의 인터페이스 호환성을 제공하는 패턴입니다. 이 패턴은 기존 클래스나 라이브러리를 재사용하려는 상황에서 해당 클래스나 라이브러리의 인터페이스가 기존 시스템과 호환되지 않을 때, 새로운 시스템에서 기존 클래스나 라이브러리를 사용할 수 있도록 하기 위해 사용됩니다.
쉽게 말해 어댑터를 이용해 110V와 220V의 호환이 가능한 것을 생각하면 쉽습니다.

어댑터 패턴의 구성요소

Target Interface

기존 시스템에서 사용하고 있는 인터페이스입니다. 이 인터페이스를 구현하면서 새로운 시스템에서 재사용하려는 클래스나 라이브러리를 사용할 수 있도록 합니다.

Adaptee Interface

새로운 시스템에서 재사용하려는 클래스나 라이브러리의 인터페이스입니다. 이 인터페이스는 기존 시스템에서 사용하고 있는 인터페이스와 호환되지 않을 수 있습니다.

Adapter

Target 인터페이스를 구현하면서 Adaptee 인터페이스를 호출합니다. Adapter는 Target 인터페이스를 기존 시스템에서 사용하면서 Adaptee 인터페이스를 호출하고, 호출된 결과를 Target 인터페이스로 반환합니다.

어댑터 패턴 구조

객체 어댑터

클래스 어댑터

어댑터 패턴 코드

// Target Interface
interface Power {
    void supplyPower(int voltage);
}

// Adaptee Interface
interface Power220VInterface {
    void supplyPower220V();
}

// Adaptee Class
class Power220V implements Power220VInterface {
    public void supplyPower220V() {
        System.out.println("220V Power Supplied");
    }
}

// Adapter Class
class PowerAdapter implements Power {
    private Power220VInterface power220V;

    public PowerAdapter(Power220VInterface power220V) {
        this.power220V = power220V;
    }

    @Override
    public void supplyPower(int voltage) {
        if (voltage == 110) {
            System.out.println("Adapter converts 110V to 220V");
            power220V.supplyPower220V();
        } else {
            System.out.println("Invalid Voltage");
        }
    }
}

// Client Code
public class Main {
    public static void main(String[] args) {
        // Adaptee
        Power220VInterface power220V = new Power220V();

        // Adapter
        Power power = new PowerAdapter(power220V);

        // Client
        power.supplyPower(110);
    }
}

위 예제를 실행하면, Power220V 객체의 supplyPower220V() 메서드가 호출되어 "220V Power Supplied"라는 출력이 나오게 됩니다.

참고 사이트


어댑터 패턴
[Design Pattern] Adapter(어댑터) 패턴이란?

profile
끊임없이 노력하는 개발자

0개의 댓글