桥接模式(Bridge)

Posted by Jfson on 2018-06-22

桥接模式是关于优先于继承的组合。实现细节从层次结构推送到具有单独层次结构的另一个对象。将抽象部分与实现部分分离,使它们都可以独立的变化

桥接模式是软件工程中使用的设计模式,旨在“将抽象与其实现分离,以便两者可以独立变化”

示例:画圆。同时需要多个元素拼接,但又不想复杂继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//桥接实现接口
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
//创建实现了 DrawAPI 接口的实体桥接实现类。
//RedCircle.java
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 +"]");
}
}
//GreenCircle.java
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 +"]");
}
}
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
//使用 Shape 和 DrawAPI 类画出不同颜色的圆。
//BridgePatternDemo.java
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}


pv UV: