https://www.ecourse.co.kr/courses/cpp_designpattern/lessons/adaptor/
C++ Design Pattern → adaptor - ecourse
www.ecourse.co.kr
Adapter는 구조 패턴으로, 인터페이스를 클라이언트가 기대하는 형태의 인터페이스로 변환해주는 기능을 한다.
class CoolText
{
std::string text;
//...
public:
CoolText(const std::string& text) : text(text) {}
void show() { std::cout << text << std::endl; }
//...
};
문자열을 보관해 두었다가, 다양한 기능을 제공하여 문자열을 출력해주는 CoolText가 있고, 해당 클래스를 오래 전부터 사용해 왔다고 가정해 보자.
struct Shape
{
virtual ~Shape() {}
virtual void drow() = 0;
};
class Rect : Shape
{
public:
void drow() override { std::cout << "draw Rect" << std::endl; }
};
class Circle : Shape
{
public:
void drow() override { std::cout << "draw Circle" << std::endl; }
};
그리고 어떠한 도형 편집기 시스템이 있는데, 해당 시스템에 사용할 도형들은 반드시 Shape을 상속받아 drow를 구현해야 한다고 가정해 보자. 이때 도형 편집기 시스템에 CoolText와 같은 기능을 추가하고 싶을 때, 새롭게 구현하지 않고 기존 클래스를 이용하기 위해 어댑터를 사용할 수 있다.
class ClsAdapter : public CoolText, public Shape
{
public:
ClsAdapter(const std::string& text) : CoolText(text) {}
void drow() override { CoolText::show(); }
};
위 코드를 보면, ClsAdapter는 CoolText를 상속 받음으로써, CoolText의 기능을 모두 사용할 수 있고, Shape을 상속 받은 후 drow를 override함으로써 도형 편집기에서 사용할 수 있도록 하였다. 이때 drow를 직접 구현하지 않고, CoolText의 show를 사용한 것이 핵심이다. 이처럼 CoolText의 기능을 그대로 사용하되, 도형 편집기의 요구 조건을 만족하게 해주는 것이 어댑터이다. 특히 위와 같이 상속을 통해 구현한 어댑터를 클래스 어댑터라고 하고, 클래스에 대한 인터페이스를 변경할 때 사용할 수 있다.
class ObjAdapter : public Shape
{
CoolText* ct;
public:
ObjAdapter(CoolText* ct, const std::string& text) : ct(ct) {}
void drow() override { ct->show(); }
};
한편 CoolText를 상속받지 않고, CoolText의 포인터를 맴버로 포함해서 사용하는 방식을 객체 어댑터라고 한다. 객체 어댑터는 이미 생성돼 있던 CoolText의 객체를 이용할 수 있는 장점이 있고, 객체에 대한 인터페이스를 변경할 때 사용할 수 있다.
'Programing > Design Pattern' 카테고리의 다른 글
template method (0) | 2025.02.10 |
---|---|
shape #2 (0) | 2025.01.26 |
dynamic_casting (0) | 2025.01.17 |
upcasting (0) | 2025.01.17 |
constructor (0) | 2025.01.16 |