桥接模式(Bridge Pattern)是用于把抽象化与实现化解耦,使得二者可以独立变化
桥接模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类,这两种类型的类可被结构化改变而互不影响
桥接模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦
1. 意图
将抽象部分与实现部分分离,使它们都可以独立的变化
2. 主要解决
在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活
3. 何时使用
4. 如何解决
把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合
5. 关键代码
6. 应用实例
7. 优点
8. 缺点
9. 使用场景
10. 注意事项
DrawAPI
接口和实现了DrawAPI
接口的实体类RedCircle
、GreenCircle
;Shape
是一个抽象类,将使用DrawAPI
的对象;BridgePatternDemo
使用Shape
类来画出不同颜色的圆;我们通过下面的实例来演示桥接模式(Bridge Pattern)
的用法: 可以使用相同的抽象类方法但是不同的桥接实现类,来画出不同颜色的圆
1. 创建桥接实现接口.
DrawAPI.java
package com.demo.gof;
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
2. 创建实现了 DrawAPI 接口的实体桥接实现类
RedCircle.java
package com.demo.gof;
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
package com.demo.gof;
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 +"]");
}
}
3. 使用 DrawAPI 接口创建抽象类 Shape
Shape.java
package com.demo.gof;
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
4. 创建实现了 Shape 接口的实体类
Circle.java
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
5. 使用 Shape 和 DrawAPI 类画出不同颜色的圆
BridgePatternDemo.java
package com.demo.gof;
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();
}
}
编译运行以上 Java 范例,输出结果如下
$ javac -d . src/main/com.demo/gof/BridgePatternDemo.java
$ java com.demo.gof.BridgePatternDemo
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]