티스토리 뷰
Bridge Pattern(가교패턴)은 구조패턴의 하나로, 추상과 구현을 분리하여 다양성을 가질수 있도록하는 패턴이다. 가교패턴을 사용하면, 런타임에 구현방법을 선택할 수 있고, 추상과 구현이 분리 되어있기 때문에 추상개념만 연결하면 독립적으로 확장하는게 쉽다.
가교패턴을 살펴보면, 기본 구조(꼴)이 다음과 같이 보인다.
추상을 만들고 이를 상속하는 컨크리트클래스를 만들어서 구현한다. 이와 관련된 예시를 생각해보았으나 잘 생각나지 않아 위키에 있는 예제코드(조금 바꿈) 살펴보겠다.
기본적으로 추상으로써, DrawingAPI라는 인터페이스를 만들어서, 이를 상속받는 DrawingAPI1과 DrawingAPI2를 만들어 구현한다. (여기서 구현부는 출력만 되도록 되있다.)
public interface DrawingAPI { public void draw(int x, int y, int r); }
public class DrawingAPI1 implements DrawingAPI { @Override public void draw(int x, int y, int r) { // TODO Auto-generated method stub System.out.format("DrawingAPI1) x = %d, y = %d, radius = %d\n", x, y, r); } }
public class DrawingAPI2 implements DrawingAPI { @Override public void draw(int x, int y, int r) { // TODO Auto-generated method stub System.out.format("DrawingAPI2) x = %d, y = %d, radius = %d\n", x, y, r); } }
이후 DrawingAPI를 사용하는 Shape를 만들어보자. Shape는 추상클래스로 생성하며, circle이 상속받는 클래스가 된다.
public abstract class Shape { DrawingAPI drawingAPI; public void useAPI(DrawingAPI api) { drawingAPI = api; } public abstract void draw(); }
public class circle extends Shape { int x, y, r; public circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; }; public circle(int x, int y, int r, DrawingAPI api) { this.x = x; this.y = y; this.r = r; drawingAPI = api; } @Override public void draw() { try { drawingAPI.draw(x, y, r); } catch (NullPointerException e) { System.out.println("you must call useAPI()"); } } }
public class bridgePattern { public static void main(String[] args) { Shape shape1, shape2; shape1 = new circle(10, 10, 20); shape2 = new circle(10, 10, 30); shape1.useAPI(new DrawingAPI1()); shape2.useAPI(new DrawingAPI2()); shape1.draw(); shape2.draw(); } }
'Paradigm > OOP' 카테고리의 다른 글
[객체지향] Proxy Pattern (0) | 2014.08.19 |
---|---|
[객체지향] PrototypePattern (0) | 2014.08.05 |
[객체지향] Abstract Factory Pattern (0) | 2014.08.04 |
[OOP] Refactoring (0) | 2013.11.06 |
[OOP] Law of demeter (0) | 2013.10.30 |
댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
- Total
- Today
- Yesterday