2015년 12월 27일 일요일

Bridge Pattern (가교 패턴)

의도
  • 구현에서 추상을 분리하여, 이들을 독립적으로 다양성을 가질 수 있도록 하는 패턴
이럴 때 사용하자.
  • 인터페이스와 구현 사이의 지속적인 종속 관계를 피하고 싶을 때
  • 인터페이스와 구현부 모두가 독립적으로 서브클래싱을 통해 확장되어야 할 때
  • 구현부 수정이 다른 클래스에 영향을 주지 않아야 할 때
  • 구현부를 은닉하길 원할 때
장점은?
  • 인터페이스와 구현을 분리시켜준다
  • 분리됨으로써 설계가 좀더 계층적 구조적으로 될 수 있다
  • 인터페이스와 구현부가 별도의 상속 구조를 가지므로, 서로 독립적인 확장이 가능하다
  • 구현부 세부 사항을 숨길 수 있다
코드
DrawingAPI 클래스
class DrawingAPI
{
public:
   virtual void drawCircle(double nX, double nY, double nRadius) = 0;
};

DrawingAPI1 클래스
class DrawingAPI1 : public DrawingAPI
{
   virtual void drawCircle(double nX, double nY, double nRadius) {
      cout << "===================" << endl;
      cout << "API1 Cricle" << endl;
      cout << "x : " << nX << endl;
      cout << "y : " << nY << endl;
      cout << "radius : " << nRadius << endl;
      cout << "===================" << endl;
   }
};

DrawingAPI2 클래스
class DrawingAPI2 : public DrawingAPI
{
   virtual void drawCircle(double nX, double nY, double nRadius) {
      cout << "===================" << endl;
      cout << "API2 Cricle" << endl;
      cout << "x : " << nX << endl;
      cout << "y : " << nY << endl;
      cout << "radius : " << nRadius << endl;
      cout << "===================" << endl;
   }
};

Shape 클래스
class Shape
{
public:
   virtual void draw() = 0;
   virtual void resizeByPercentage(double nPercentage) = 0;

protected:
   DrawingAPI* m_pDrawingAPI;
};

CircleShape 클래스
class CircleShape : public Shape
{
public:
   CircleShape(double nX, double nY, double nRadius, DrawingAPI* pDrawingAPI) {
      m_pDrawingAPI = pDrawingAPI;
      m_nX = nX;
      m_nY = nY;
      m_nRadius = nRadius;
   }
   virtual void draw() {
      m_pDrawingAPI->drawCircle(m_nX, m_nY, m_nRadius);
   }
   virtual void resizeByPercentage(double nPercentage) {
      m_nRadius *= (1.0 + (nPercentage / 100.0));
   }

private:
   double m_nX;
   double m_nY;
   double m_nRadius;
};

실행부분
void main()
{
   auto_ptr<DrawingAPI> pDrawingAPI1(new DrawingAPI1());
   auto_ptr<DrawingAPI> pDrawingAPI2(new DrawingAPI2());

   auto_ptr<Shape> pCircleShape1(new CircleShape(3, 2, 10, pDrawingAPI1.get()));
   auto_ptr<Shape> pCircleShape2(new CircleShape(5, 1, 20, pDrawingAPI2.get()));

   pCircleShape1->draw();
   pCircleShape2->draw();
}

UML - class 다이어그램

참고
  • GoF의 디자인 패턴(개정판) 재사용성을 지닌 객체지향 소프트웨어의 핵심요소
  • http://kimsunzun.tistory.com/19
  • http://blog.naver.com/drifterz303/90194293283
  • https://en.wikipedia.org/wiki/Bridge_pattern

댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.