C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
이 글의 핵심
C++ Adapter Pattern 완벽 가이드에 대한 실전 가이드입니다. 개념부터 실무 활용까지 예제와 함께 상세히 설명합니다.
Adapter Pattern이란? 왜 필요한가
해외에서 산 전자제품과 콘센트 모양이 맞지 않을 때 어댑터로 모양만 바꿔 꽂듯이, 소프트웨어에서도 호출 규약(Target) 과 실제 구현(Adaptee) 이 다를 때 중간에서 맞춰 주는 역할이 어댑터입니다. 아래에서는 그 불일치가 코드로 어떻게 드러나는지부터 살펴보겠습니다.
구조 패턴 시리즈에서 다른 구조 패턴과의 관계를 정리했고, JavaScript에서도 API를 맞추는 식의 통합이 자주 나옵니다.
문제 시나리오: 호환되지 않는 인터페이스
문제는 다음과 같습니다. 기존 라이브러리가 노출하는 함수 이름·매개변수 형태가, 우리가 이미 설계해 둔 추상 인터페이스와 맞지 않을 때가 있습니다.
// 내 코드가 기대하는 인터페이스
class MediaPlayer {
public:
virtual void play(const std::string& filename) = 0;
};
// 기존 라이브러리 (호환 안 됨)
class VLCPlayer {
public:
void playVLC(const std::string& filename) { /* ... */ }
};
// 어떻게 VLCPlayer를 MediaPlayer로 사용?
해결: Adapter Pattern은 인터페이스를 변환합니다. Adapter가 Target 인터페이스를 구현하고, 내부에서 Adaptee를 호출합니다.
// Adapter
class VLCAdapter : public MediaPlayer {
public:
VLCAdapter(std::unique_ptr<VLCPlayer> player)
: vlc(std::move(player)) {}
void play(const std::string& filename) override {
vlc->playVLC(filename); // 인터페이스 변환
}
private:
std::unique_ptr<VLCPlayer> vlc;
};
핵심 개념: Adapter Pattern은 호환되지 않는 인터페이스를 연결하는 다리 역할을 합니다. 레거시 시스템 통합이나 서드파티 라이브러리 사용 시 필수적인 패턴입니다.
목차
1. 객체 어댑터
객체 어댑터는 상속으로 타입을 합치지 않고, 멤버로 VLCPlayer 같은 구현체를 들고 있는 방식(조합) 입니다. 구현을 바꾸거나 목(mock)으로 바꿀 때 어댑터 한곳만 건드리면 되므로, 실무에서는 이 형태를 가장 많이 권장합니다.
조합 방식
아래 예제에서는 MediaPlayer 하나의 인터페이스로 VLCAdapter와 MP4Adapter를 바꿔 끼울 수 있게 하여, 호출부(player->play)는 동일한 문장을 유지합니다.
#include <iostream>
#include <memory>
#include <string>
class MediaPlayer {
public:
virtual void play(const std::string& filename) = 0;
virtual ~MediaPlayer() = default;
};
class VLCPlayer {
public:
void playVLC(const std::string& filename) {
std::cout << "Playing VLC: " << filename << '\n';
}
};
class MP4Player {
public:
void playMP4(const std::string& filename) {
std::cout << "Playing MP4: " << filename << '\n';
}
};
class VLCAdapter : public MediaPlayer {
public:
VLCAdapter() : vlc(std::make_unique<VLCPlayer>()) {}
void play(const std::string& filename) override {
vlc->playVLC(filename);
}
private:
std::unique_ptr<VLCPlayer> vlc;
};
class MP4Adapter : public MediaPlayer {
public:
MP4Adapter() : mp4(std::make_unique<MP4Player>()) {}
void play(const std::string& filename) override {
mp4->playMP4(filename);
}
private:
std::unique_ptr<MP4Player> mp4;
};
int main() {
std::unique_ptr<MediaPlayer> player;
player = std::make_unique<VLCAdapter>();
player->play("movie.vlc");
player = std::make_unique<MP4Adapter>();
player->play("movie.mp4");
}
2. 클래스 어댑터
클래스 어댑터는 다중 상속을 사용하는 방식입니다. C++에서는 가능하지만, 객체 어댑터보다 유연성이 떨어집니다.
다중 상속 방식
#include <iostream>
#include <string>
class MediaPlayer {
public:
virtual void play(const std::string& filename) = 0;
virtual ~MediaPlayer() = default;
};
class VLCPlayer {
public:
void playVLC(const std::string& filename) {
std::cout << "Playing VLC: " << filename << '\n';
}
};
// 클래스 어댑터 (다중 상속)
class VLCAdapter : public MediaPlayer, private VLCPlayer {
public:
void play(const std::string& filename) override {
playVLC(filename); // 직접 호출
}
};
int main() {
MediaPlayer* player = new VLCAdapter();
player->play("movie.vlc");
delete player;
}
장점: Adaptee 객체를 저장할 필요 없음. 단점: 다중 상속, Adaptee가 final이면 불가.
3. 레거시 코드 통합
레거시 시스템을 현대적인 코드베이스에 통합할 때 Adapter Pattern이 빛을 발합니다. 기존 코드를 수정하지 않고도 새로운 인터페이스로 사용할 수 있습니다.
오래된 API를 현대적 인터페이스로
#include <iostream>
#include <string>
#include <memory>
// 레거시 API (C 스타일)
class LegacyRectangle {
public:
void draw(int x1, int y1, int x2, int y2) {
std::cout << "Legacy: Rectangle from (" << x1 << "," << y1
<< ") to (" << x2 << "," << y2 << ")\n";
}
};
// 현대적 인터페이스
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() = default;
};
class Rectangle : public Shape {
public:
Rectangle(int x, int y, int w, int h)
: x_(x), y_(y), width_(w), height_(h) {}
void draw() override {
std::cout << "Modern: Rectangle at (" << x_ << "," << y_
<< ") size " << width_ << "x" << height_ << '\n';
}
private:
int x_, y_, width_, height_;
};
// Adapter
class LegacyRectangleAdapter : public Shape {
public:
LegacyRectangleAdapter(int x, int y, int w, int h)
: x_(x), y_(y), width_(w), height_(h),
legacy(std::make_unique<LegacyRectangle>()) {}
void draw() override {
legacy->draw(x_, y_, x_ + width_, y_ + height_);
}
private:
int x_, y_, width_, height_;
std::unique_ptr<LegacyRectangle> legacy;
};
int main() {
std::unique_ptr<Shape> shape1 = std::make_unique<Rectangle>(10, 20, 100, 50);
shape1->draw();
std::unique_ptr<Shape> shape2 = std::make_unique<LegacyRectangleAdapter>(10, 20, 100, 50);
shape2->draw();
}
4. 자주 발생하는 문제와 해결법
문제 1: 메모리 누수
증상: 메모리 누수.
원인: raw pointer 사용.
// ❌ 잘못된 사용
class Adapter {
Adaptee* adaptee; // 누가 delete?
};
// ✅ 올바른 사용
class Adapter {
std::unique_ptr<Adaptee> adaptee;
};
문제 2: 양방향 어댑터
증상: 순환 의존성.
원인: A를 B로, B를 A로 변환.
// ✅ 해결: 공통 인터페이스
class CommonInterface {
virtual void operation() = 0;
};
class AdapterA : public CommonInterface { /* ... */ };
class AdapterB : public CommonInterface { /* ... */ };
5. 프로덕션 패턴
패턴 1: 팩토리와 결합
class MediaPlayerFactory {
public:
static std::unique_ptr<MediaPlayer> create(const std::string& type) {
if (type == "vlc") {
return std::make_unique<VLCAdapter>();
} else if (type == "mp4") {
return std::make_unique<MP4Adapter>();
}
return nullptr;
}
};
auto player = MediaPlayerFactory::create("vlc");
player->play("movie.vlc");
패턴 2: 템플릿 어댑터
template<typename Adaptee>
class GenericAdapter : public MediaPlayer {
public:
GenericAdapter() : adaptee(std::make_unique<Adaptee>()) {}
void play(const std::string& filename) override {
adaptee->playSpecific(filename);
}
private:
std::unique_ptr<Adaptee> adaptee;
};
6. 완전한 예제: 결제 시스템
#include <iostream>
#include <memory>
#include <string>
class PaymentProcessor {
public:
virtual bool processPayment(double amount) = 0;
virtual ~PaymentProcessor() = default;
};
// 레거시 PayPal API
class PayPalAPI {
public:
bool sendPayment(double dollars) {
std::cout << "PayPal: Processing $" << dollars << '\n';
return true;
}
};
// 레거시 Stripe API
class StripeAPI {
public:
bool charge(int cents) {
std::cout << "Stripe: Charging " << cents << " cents\n";
return true;
}
};
// 새로운 Square API
class SquareAPI {
public:
bool makePayment(const std::string& amount) {
std::cout << "Square: Payment of " << amount << '\n';
return true;
}
};
// Adapters
class PayPalAdapter : public PaymentProcessor {
public:
PayPalAdapter() : paypal(std::make_unique<PayPalAPI>()) {}
bool processPayment(double amount) override {
return paypal->sendPayment(amount);
}
private:
std::unique_ptr<PayPalAPI> paypal;
};
class StripeAdapter : public PaymentProcessor {
public:
StripeAdapter() : stripe(std::make_unique<StripeAPI>()) {}
bool processPayment(double amount) override {
int cents = static_cast<int>(amount * 100);
return stripe->charge(cents);
}
private:
std::unique_ptr<StripeAPI> stripe;
};
class SquareAdapter : public PaymentProcessor {
public:
SquareAdapter() : square(std::make_unique<SquareAPI>()) {}
bool processPayment(double amount) override {
return square->makePayment("$" + std::to_string(amount));
}
private:
std::unique_ptr<SquareAPI> square;
};
class PaymentService {
public:
PaymentService(std::unique_ptr<PaymentProcessor> processor)
: processor_(std::move(processor)) {}
void checkout(double amount) {
std::cout << "Processing checkout for $" << amount << '\n';
if (processor_->processPayment(amount)) {
std::cout << "Payment successful!\n\n";
} else {
std::cout << "Payment failed!\n\n";
}
}
private:
std::unique_ptr<PaymentProcessor> processor_;
};
int main() {
PaymentService service1(std::make_unique<PayPalAdapter>());
service1.checkout(99.99);
PaymentService service2(std::make_unique<StripeAdapter>());
service2.checkout(49.50);
PaymentService service3(std::make_unique<SquareAdapter>());
service3.checkout(29.99);
}
정리
| 개념 | 설명 |
|---|---|
| Adapter Pattern | 인터페이스를 변환 |
| 목적 | 호환되지 않는 인터페이스 통합 |
| 구조 | Target, Adapter, Adaptee |
| 장점 | 레거시 통합, OCP 준수, 재사용성 |
| 단점 | 클래스 증가, 간접 참조 |
| 사용 사례 | 레거시 통합, 서드파티 라이브러리, API 변환 |
Adapter Pattern은 호환되지 않는 인터페이스를 통합하는 필수 패턴입니다.
FAQ
Q1: Adapter Pattern은 언제 쓰나요?
A: 레거시 코드 통합, 서드파티 라이브러리 사용, 인터페이스 불일치 해결 시 사용합니다.
Q2: 객체 어댑터 vs 클래스 어댑터?
A: 객체 어댑터는 조합(권장), 클래스 어댑터는 다중 상속(C++ 가능).
Q3: Decorator와 차이는?
A: Adapter는 인터페이스 변환, Decorator는 기능 추가에 집중합니다.
Q4: Facade와 차이는?
A: Adapter는 단일 클래스 변환, Facade는 서브시스템 단순화에 집중합니다.
Q5: 성능 오버헤드는?
A: 간접 참조 1회, 무시할 수 있는 수준입니다.
Q6: Adapter Pattern 학습 리소스는?
A:
- "Design Patterns" by Gang of Four
- "Head First Design Patterns" by Freeman & Freeman
- Refactoring Guru: Adapter Pattern
한 줄 요약: Adapter Pattern으로 호환되지 않는 인터페이스를 통합할 수 있습니다. 다음으로 Proxy Pattern을 읽어보면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합
- C++ Facade 패턴 완벽 가이드 | 복잡한 서브시스템을 하나의 간단한 인터페이스로
- C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기