pattern2018. 7. 19. 15:28

Bridge pattern



-implementaion으로부터 abstraction을 decouple할 때 사용.

-structural pattern으로 bridge structure를 implement 및 abstract class에 제공.


-두 타입의 class들은 구조적으로 서로에게 영향을 주지 않고 변경될 수 있다.(변경에 대하여 열린 구조로 변경됨)




DrawAPI : bridge implementer interface.

RedCircle, GreenCircle : concrete bridge implementer classes

Shape : abstract class 

Circle : concrete class implementing the Shape interface.



에제 설명 :

 

Shape 과 DrawAPI가 brige structure를 가지며,

Shape는 abstraction hierarchy, DrawAPI를 implementation hierarchy로 분리됨.

Shape은 DrawAPI를 멤버로 가져가 concrete class인 Circle 구현에 사용한다.


각 hierarchy는 서로 영향을 받지 않은채 수정이 가능하다.

간단히 표현하자면, Shape은 interface부분(껍데기), DrawAPI는 implementation이 구체화된 부분(실질적 내용)으로 볼 수 있다.


Main 호출 부분에선 어떤 implementation을 사용할지 결정할 수 있다.

그리고 실제 interface를 사용하는 부분에서는 이와는 독립적으로 method를 호출한다.




	Shape shape1 = new Circle(1,2,3, new RedCircle());
	Shape shape2 = new Circle(10,20,30, new GreenCircle());
	shape1.draw();
	shape2.draw();


Shape과 DrawAPI의 bridge structure 관계를 확인.
abstract area.
Shape.java
public abstract class Shape {
    protected DrawAPI mDrawAPI;
    protected Shape( DrawAPI d ){
        mDrawAPI=d;
    }
    public abstract String draw();
}


implementation area.
DrawAPI.java
public interface DrawAPI {
    public final String TAG = "hello";
    public void drawCircle(int radius, int x, int y);
}


Shape의 concrete implementation.
public class Circle extends Shape {
    private int x;
    private int y;
    private int radius;

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

    @Override
    public String draw() {
        mDrawAPI.drawCircle(radius,x,y);
        return "draw";
    }
}


concrete implementation 1.
public class RedCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        Log.d(TAG, "Draw RedCircle : x"+x+" y="+y+" radius="+radius);
    }
}


concrete implementation 2.
public class GreenCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        Log.d(TAG, "Draw GreenCircle : x"+x+" y="+y+" radius="+radius);
    }
}

결과:

07-19 15:14:36.059 13590 13590 D hello   : Draw RedCircle : x1 y=2 radius=3
07-19 15:14:36.059 13590 13590 D hello   : Draw GreenCircle : x10 y=20 radius=30

출처 : 


'pattern' 카테고리의 다른 글

Composite pattern  (0) 2018.07.19
Filter pattern or Criteria pattern  (0) 2018.07.19
Adapter pattern  (0) 2018.07.19
Prototype pattern  (0) 2018.07.18
Builder pattern  (0) 2018.07.18
Posted by easy16