桥接模式是一种结构型设计模式。它经过使用封装、聚合及继承等行为让不一样的类承担不一样的职责。它的主要特色是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而能够保持各部分的独立性以及应对他们的功能扩展。java
在学习的时候,看到了一个很不错的例子,就拿来分享一下。编程
1.建立桥接实现接口设计模式
public interface DrawAPI { public void drawCircle(int radius, int x, int y); }
2.建立接口实现类ide
建立实现了 DrawAPI 接口的实体桥接实现类。学习
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.建立桥接接口抽象类this
使用 DrawAPI 接口建立抽象类 Shape。设计
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); }
4.建立抽象类的实例code
建立实现了 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(); } }
(1)实现了抽象和实现部分的分离
桥接模式分离了抽象部分和实现部分,从而极大的提供了系统的灵活性,让抽象部分和实现部分独立开来,分别定义接口,这有助于系统进行分层设计,从而产生更好的结构化系统。对于系统的高层部分,只须要知道抽象部分和实现部分的接口就能够了。
(2)更好的可扩展性
因为桥接模式把抽象部分和实现部分分离了,从而分别定义接口,这就使得抽象部分和实现部分能够分别独立扩展,而不会相互影响,大大的提供了系统的可扩展性。
(3)可动态的切换实现
因为桥接模式实现了抽象和实现的分离,因此在实现桥接模式时,就能够实现动态的选择和使用具体的实现。
(4)实现细节对客户端透明,能够对用户隐藏实现细节。
(1)桥接模式的引入增长了系统的理解和设计难度,因为聚合关联关系创建在抽象层,要求开发者针对抽象进行设计和编程。
(2)桥接模式要求正确识别出系统中两个独立变化的维度,所以其使用范围有必定的局限性。