본문 바로가기

기타/Design pattern

Adapter pattern

1. Issue

● 기존의 클래스나 라이브러리 모듈을 변형하거나 수정 하지 않고 사용할 수 있는가?

 

2. Why

● 인터페이스가 다른 클래스를 사용하려면 인터페이스를 통일 시켜야 한다.

● 자신이 개발하는 모듈의 소스를 수정하는 것은 더욱 많은 비용을 발생시킨다.

● 라이브러리 모듈 같은 경우 소스코드가 없고 수정하려 해도 많은 비용이 든다.

 

3. Solution

3-1. Object Adapter 패턴

○ 존재하는 객체를 참조해서 인터페이스를 통일

 

 

class Rectangle{

public :

Rectangle() {}

void Draw() {}

};

 

class TextView{//존재하는클래스(Adaptee클래스)

public :

Rectangle GetExtent() {

return Rectangle();

}

};

 

class Shape{

public :

virtual Rectangle BoundingBox() = 0;

};

 

class LineShape : public Shape{

public :

Rectangle BoundingBox() {

return Rectangle();

}

};

 

class TextShape : public Shape {//Adapter 클래스

public :

TextShape() {

pText_ = new TextView;

}

Rectangle BoundingBox() {

return pText_->GetExtent();

}

private :

TextView *pText_;

};

 

void DisplayBoundingBox(Shape*pSelectedShape)

{

(pSelectedShape->BoundingBox()).Draw();

}

 

void main()

{

TextShape text;

DisplayBoundingBox(&texst);

}

 

3-2. Class Adapter 패턴

○ 다중 상속을 통해서 클래스를 참조

 

class TextShape : public Shape, private TextView {//Adapter 클래스

public :

Rectangle BoundingBox() {

return GetExtent();

}

 

};

 

4. Good point

4.1. Class Adapter패턴

● Adapter클래스에서 Adaptee클래스의 멤버 함수들을 Override할 수 있다.(상속관계)

● Adaptee클래스에 해당하는 별도의 객체를 생성하는 것이 불 필요하다.

4.2 Object Adapter패턴

● Adaptee클래스에 새로운 기능 추가가 편리하고 Adapter클래스에서 동일하게기능 수행 가능

 

5. Bad point

5.1. Class Adapter패턴

● Adapter클래스에 의해 접목되어 지는 Adaptee클래스가 고정적이어서 Adaptee클래스의 하위 클래스가 잇는 경우 이들에 대해서는 동작하지 않는다.

5.2 Object Adapter패턴

● Adaptee클래스의 멤버 함수를 Override하려면 Adaptee클래스를 상속하는 하위 클래스를 정의하고 이를 다시 사용하는 형태가 되어야 한다.

 

6. A point to be considered (고려사항)

● Class Adapter패턴의 경우 다중 상속으로 이루어지는데 Client에게 공개될 클래스는 public으로 상속하고 내부 구현을 위해 사용할 클래스는 private형태로 상속하는 것이 일반적인 방법이다. 두가지 자료형 모두 사용을 위해서는 둘다 public으로 상속을 받으면 되지만 그런 경우 종종 혼란을 초래할 수 있다.

● Adapter클래스와 Adaptee클래스의 객체생성 시기가 같아서 생명 주기를 동일하게 관리할 수 있는 장점이 있지만 불필요한 시점에도 Adaptee클래스를 유지 관리해야 한다. 이를 피하기 위해 Adapter클래스에 Adaptee클래스를 생성하고 소멸할 수 있는 인터페이스를 별도로 정의할 수 있지만 그 경우에는 객체 사용전에 Adaptee에 대한 객체가 생성되어있는지 확인해야 하는 불편이 있다.

 

6. Reference

http://blog.naver.com/mobius81?Redirect=Log&logNo=33497753

 

'기타 > Design pattern' 카테고리의 다른 글

Singleton pattern  (0) 2009.04.27
Decorator pattern  (0) 2009.04.27
Builder pattern  (0) 2009.04.27
Abstract Factory pattern  (0) 2009.04.27
소프트웨어 개발 기본 요소  (0) 2009.04.27