728x90
구조 패턴 - 어댑터
어댑터 패턴
- 호환되지 않은 인터페이스가 있는 객체들이 함께 협업할 수 있는 구조 설계 패턴
- 기존 인터페이스를 구현하여 호환이 필요한 객체를 감싸 호환되게 만든다.
- 중간 다리 역할(ex) 전압변환기)을 한다.
문제
- 개발한 주식 시장 모니터링 앱은
XML
형식의 주식 데이터를 다운로드하여 차트와 다이어그램을 표시한다. - 새로운 데이터 형식을 지원하기 시작한다고 가정할 때 (ex)
JSON
) 기존 코드를 중단시키지 않고 동작시킬 수 있는 방법이 필요하다.
해결방법 : 어댑터(Adapter
) 만들기
어댑터
: 다른 객체가 이해할 수 있도록 인터페이스를 변환한다.- 작성 방법
-
- 기존 객체 중 하나와 호환되는 인터페이스를 가져온다.
- 어댑터는 새로운 객체를 감싸고 기존 인터페이스를 구현한다.
- 클라이언트는 어댑터가 동작하는지 알지 못한다. (기존 인터페이스와 동일하기 때문)
-
코드로 작성해본다면 아래와 같다.
- Target Interface
public interface MonitoringSystem {
void draw();
}
- 기존 구현체
public class XMLStockMonitoringSystem implements MonitoringSystem {
public void draw() {
}
}
- Adaptee
public class JSONStockMonitoringSystem {
public void drawJSON() {
}
}
- Adapter
public class JSONStockMonitoringSystemAdapter implements MonitoringSystem {
private final JSONStockMonitoringSystem jsonStockMonitoringSystem;
public JSONStockMonitoringSystemAdapter(final JSONStockMonitoringSystem jsonStockMonitoringSystem) {
this.jsonStockMonitoringSystem = jsonStockMonitoringSystem;
}
@Override
public void draw() {
jsonStockMonitoringSystem.drawJSON();
}
}
- ApplicationCode
public class App {
public static void main(String[] args) {
// 기존 시스템 - XML
MonitoringSystem monitoringSystem = new XMLStockMonitoringSystem();
// 새로운 시스템 - JSON 사용
JSONStockMonitoringSystem jsonStockMonitoringSystem = new JSONStockMonitoringSystem();
// 어댑터를 이용하면 참조 타입이 같다!
MonitoringSystem jsonMonitoringSystem = new JSONStockMonitoringSystemAdapter(jsonStockMonitoringSystem);
// 사용하기
monitoringSystem.draw();
jsonMonitoringSystem.draw();
}
}
XMLStockMonitoringSystem과 JSONStockMonitoringSystem는 다른 시스템이지만 어댑터를 통해 같은 인터페이스로 참조할 수 있다.
구조 - 그림으로 알아보기
Client
: 프로그램 기존 비즈니스 로직Client interface
: 클라이언트 코드가 기대하는 인터페이스Service
: 호환되지 않은 인터페이스를 가진 서비스- 외부 시스템이나 변경할 수 없는 레거시 코드
Adapter
: 서비스 객체를 감싸면서 클라이언트 인터페이스 구현- 두 시스템간 변환 작업 수행
적용점
- 서로 다른 인터페이스를 가진 객체끼리 협력해야하는데, 외부 코드(라이브러리)라서 수정할 수 없다면 어댑터를 사용하자.
- 어댑터는 번역기처럼 동작하여 서로 다른 인터페이스를 가진 시스템들이 함께 동작할 수 있게 해준다.
- 사용할 인터페이스를 구현하지 않은 하위 클래스를 재사용하고 싶을 경우 어댑터를 이용해 사용할 수 있다.
- 누락된 기능도 추가할 수 있다.
구현 방법
-
- 호환되지 않은 인터페이스가 있는 두 가지 이상의 클래스가 있는지 확인한다.
- 클라이언트 인터페이스를 선언하고 클라이언트가 서비스와 통신하는 방법을 설명한다.
- 어댑터 클래스를 생성하여 클라이언트 인터페이스를 따르도록 구현한다.
- 어댑터 클래스에 서비스 객체에 대한 참조를 저장하고, 인터페이스의 메서드를 하나씩 구현한다.
- 클라이언트는 호환되는 인터페이스를 이용해 어댑터를 사용할 수 있다.
Reference
https://refactoring.guru/design-patterns/adapter
Adapter
/ Design Patterns / Structural Patterns Adapter Also known as: Wrapper Intent Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate. Problem Imagine that you’re creating a stock market monitoring app. The
refactoring.guru
728x90
'설계 > 디자인 패턴' 카테고리의 다른 글
[디자인패턴] 생성 패턴 - 싱글톤 패턴 (0) | 2025.02.18 |
---|---|
[디자인패턴] 생성 패턴 - 프로토타입 패턴 (2) | 2025.02.17 |
[디자인패턴] 생성 패턴 - 빌더 패턴 (0) | 2025.02.14 |
[디자인패턴] 생성 패턴 : 추상 팩토리 패턴 (0) | 2025.02.13 |
[디자인패턴] 생성 패턴 : 팩토리 메서드 패턴 (1) | 2025.02.12 |