본문 바로가기

프로그래밍/자바 디자인 패턴

자바 디자인 패턴 튜토리얼 - 구조 설계 패턴 - 브릿지 패턴

반응형

브릿지 패턴은 구현과 정의를 분리합니다. 이런 패턴을 구조적인 패턴이라 합니다.

이 패턴은 브리지 역할을하는 인터페이스를 포함합니다. 브릿지는 구상 클래스를 인터페이스 구현으로부터 독립시킵니다.

두 가지 유형의 클래스는 서로 영향을주지 않고 변경 될 수 있습니다.

예제


interface Printer {
   public void print(int radius, int x, int y);
}
class ColorPrinter implements Printer {
   @Override
   public void print(int radius, int x, int y) {
      System.out.println("Color: " + radius +", x: " +x+", "+ y +"]");
   }
}
class BlackPrinter implements Printer {
   @Override
   public void print(int radius, int x, int y) {
      System.out.println("Black: " + radius +", x: " +x+", "+ y +"]");
   }
}
abstract class Shape {
   protected Printer print;
   protected Shape(Printer p){
      this.print = p;
   }
   public abstract void draw();  
}
class Circle extends Shape {
   private int x, y, radius;

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

   public void draw() {
      print.print(radius,x,y);
   }
}
public class Main {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new ColorPrinter());
      Shape blackCircle = new Circle(100,100, 10, new BlackPrinter());

      redCircle.draw();
      blackCircle.draw();
   }
}

위의 코드는 다음 결과를 생성합니다.

Color: 10, x:100,100]

Black: 10, x:100,100]

반응형