桥接模式
用于把抽象化与实现化解耦,使得二者可以独立变化
通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦
涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类,这两种类型的类可被结构化改变而互不影响
创建意图与使用步骤
意图:将抽象部分与实现部分分离,使它们都可以独立的变化
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化
如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。
关键代码:抽象类依赖实现类。
优点
1)抽象和实现的分离
2)优秀的扩展能力
3)实现细节对客户透明
缺点
1)桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程
2)桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性
实现
1.创建桥接实现接口
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
2.实现类
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 +"]");
}
}
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
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
4.创建实现了Shape抽象类的实体类
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;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
5.用Shape和DrawAPI类画出不同颜色的圆
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();
}
}
6.执行输出
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]
评论