브리지(Bridge)

Seo·2020년 8월 26일
0

design_pattern

목록 보기
9/11

상위문서: GoF 디자인 패턴

브리지(Bridge)

  • 상위 Category : 구조(Structural) 패턴

구현분에서 추상층을 분리하여 각자 독립적으로 변형이 가능하고 확장이 가능하도록 한다.
즉 기능 클래스 계층과 구현 클래스 계층으로 구현을 하는 패턴.
전형적인 상속을 이용한 패턴으로 확장 설계에 용이.

  • Abstraction : 기능 계층의 최상위 클래스. 구현 부분에 해당하는 클래스를 인스턴스를 가지고 해당 인스턴스를 통해 구현부분의 메서드를 호출
  • RefindAbstraction : 기능 계층에서 새로운 부분을 확장한 클래스
  • Implementor : 구현 클래스 계층, Abstraction의 기능을 구현하기 위한 인터페이스 정의
  • ConcreteImplementor : 실제 기능을 구현
// Implementor
interface DrawingAPI{
   public void drawCircle(double x, double y, double radius);
}

// ConcreteImplementor1
class DrawingAPI1 implements DrawingAPI{
   public void drawCircle(double x, double y, double radius){
      System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
   }
}

// ConcreteImplementor2
class DrawingAPI2 implements DrawingAPI{
   public void drawCircle(double x, double y, double radius){
        System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
   }
}

// Abstraction
interface Shape
{
   public void draw();                             // low-level
   public void resizeByPercentage(double pct);     // high-level
}

// Refined Abstraction
class CircleShape implements Shape
{
   private double x, y, radius;
   private DrawingAPI drawingAPI;
   public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI){
       this.x = x;  this.y = y;  this.radius = radius;
       this.drawingAPI = drawingAPI;
   }

   // low-level i.e. Implementation specific
   public void draw(){
        drawingAPI.drawCircle(x, y, radius);
   }
   // high-level i.e. Abstraction specific
   public void resizeByPercentage(double pct){
        radius *= pct;
   }
}

// Main
class BridgePattern {
   public static void main(String[] args){
       Shape[] shapes = new Shape[2];
       shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
       shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());

       for (Shape shape : shapes){
           shape.resizeByPercentage(2.5);
           shape.draw();
       }
   }
}

// 결과
// API1.circle at 1:2 7.5
// API2.circle at 5:7 27.5
profile
개발관심자

0개의 댓글