桥接模式用于把抽象化与实现化解耦,使两者可以独立变化。把这种多角度分类分离出来,让它们独立变化,减少它们之间的耦合。
桥接模式的优点是抽象和实现分离,扩展性好,实现细节对客户透明;缺点是会增加系统的理解与设计难度,聚合关系建立在抽象层,要求开发者对抽象进行设计与编程。
public interface DrawAPI {
void drawCircle(int radius, int x, int y);
}
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:" + y + "]");
}
}
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:" + y + "]");
}
}
public abstract class Shape{
DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
abstract void draw();
}
public class Circle extends Shape {
private int x, y, radius;
protected Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
public class BridgeInstance {
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
redCircle.draw();
Shape greenCircle = new Circle(50, 50, 5, new GreenCircle());
greenCircle.draw();
}
}