반응형

Design Patterns - Bridge Pattern


(원문 위치 : http://www.tutorialspoint.com/design_pattern/bridge_pattern.htm )


브릿지는 두개가 독립적으로 바뀔 수 있도록 구현으로부터 추상을 분리할 필요가 있을때 사용된다. 이 디자인 패턴의 형태는 이 패턴이 구현 클래스와 추상 클래스 사이에 브릿지 구조를 제공함으로써 구현클래스와 추상클래스를 분리하기 때문에 구조적 패턴에 포함된다.


이 패턴은 인터페이스 구현자 클래스로부터 구체적인 독립 클래스의 기능을 만드는 브릿지로써 동작하는 인터페이스를 필요로한다. 클래스의 각 형태는 서로간 영향 없이 구조적으로 대체되어질 수 있다.


동일 추상 클래스 메소드를 사용하여 다른 색을 그리지만 다른 브릿지 구현 클래스인 circle 예제를 통해 브릿지 패턴의 용도를 시현할 것이다.

Implementation

비릿지 구현자로써 동작하고 있는 DrawAPI 인터페이스와 DrawAPI 인터페이스를 구현하는 구체적 클래스 - RedCircle, GreenCircle가 있다. Shape는 추상클래스이고 DrawAPI의 객체를 사용할 것이다. DridgePatternDemo, demo 클래스는 다른 색의 원을 그리기 위해 Shape클래스를 사용할 것이다.

Bridge Pattern UML Diagram

Step 1

비릿지 구현자 인퍼테이스(bridge implementer interface)를 생성한다.

DrawAPI.java

public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}

Step 2

DrawAPI 인터페이스를 구현하는 구체적 브릿지 구현자 클래스를 생성한다.

RedCircle.java

public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}

GreenCircle.java

public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}

Step 3

DrawAPI 인터페이스를 사용하여 Shape 추상 클래스를 생성한다.

Shape.java

public abstract class Shape {
   protected DrawAPI drawAPI;
   
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();	
}

Step 4

Shape 인터페이스를 구현하는 구체적 클래스를 생성한다.

Circle.java

public class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}

Step 5

다른 색의 원을 그리기 위해 Shape와 DrawAPI를 사용한다.

BridgePatternDemo.java

public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

      redCircle.draw();
      greenCircle.draw();
   }
}

Step 6

결과를 확인한다.

Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]


반응형

+ Recent posts