상위문서: GoF 디자인 패턴
구현분에서 추상층을 분리하여 각자 독립적으로 변형이 가능하고 확장이 가능하도록 한다.
즉 기능 클래스 계층과 구현 클래스 계층으로 구현을 하는 패턴.
전형적인 상속을 이용한 패턴으로 확장 설계에 용이.
// 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