Java Bridge Pattern(桥接模式)
2017-09-29 00:58
267 查看
Java Bridge Pattern(桥接模式)
桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。
优点: 1、抽象和实现的分离。 2、优秀的扩展能力。 3、实现细节对客户透明。
缺点:桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
创建桥接实现接口。
/** * 1. 创建桥接实现接口。 * @author mazaiting */ public interface DrawAPI { /** * 画圆 * @param radius 半径 * @param x 圆心横坐标 * @param y 圆心纵坐标 */ void drawCircle(int radius, int x,int y); }
创建实现了 DrawAPI 接口的实体桥接实现类。
/** * 2. 创建实现了 DrawAPI 接口的实体桥接实现类。 * @author mazaiting */ public class GreenCircle implements DrawAPI{ public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius +", x: " +x+", y: "+ y +"]"); } } /** * 2. 创建实现了 DrawAPI 接口的实体桥接实现类。 * @author mazaiting */ public class RedCircle implements DrawAPI{ public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: red, radius: " + radius +", x: " +x+", y: "+ y +"]"); } }
使用 DrawAPI 接口创建抽象类 Shape。
/** * 3. 使用 DrawAPI 接口创建抽象类 Shape。 * @author mazaiting */ public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI) { this.drawAPI = drawAPI; } /** * 绘画 */ public abstract void draw(); }
创建实现了 Shape 接口的实体类。
/** * 4. 创建实现了 Shape 接口的实体类。 * @author mazaiting */ 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); } }
主函数验证
public class Client { 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(); } }
打印结果
Drawing Circle[ color: red, radius: 10, x: 100, y: 100] Drawing Circle[ color: green, radius: 10, x: 100, y: 100]
相关文章推荐
- Java实现(07)——桥接模式(Bridge Pattern)
- java设计模式——桥接模式(Bridge Pattern)
- Java设计模式——桥接模式(Bridge Pattern)
- Java开发中的23种设计模式之十:桥接模式(Bridge)
- Java设计模式二十一:桥模式(Bridge Pattern)
- 桥接模式(Bridge Pattern)
- 桥接模式(Bridge pattern)
- 设计模式学习笔记十二:桥接模式(Bridge Pattern)
- 桥接模式(bridge pattern)-------结构型模式
- Bridge Pattern (桥接模式)
- 桥接模式(Bridge Pattern)
- (第Ⅲ部分 结构型模式篇) 第8章 桥接模式(Bridge Pattern)
- 设计模式总结之Bridge Pattern(桥接模式)
- 桥接模式(Bridge Pattern)要点
- 第十六章 桥接模式(Bridge Pattern)
- Java设计模式之--桥接模式(bridge pattern)
- Bridge Pattern (桥接模式)
- java设计模式(九)——桥接模式(Bridge)
- 设计模式(九)-桥接模式(Bridge Pattern)——将类的功能层次结构与实现层次结构分离
- java设计模式10——桥接模式(Bridge)