开发手册 欢迎您!
软件开发者资料库

设计模式 - 桥梁模式

设计模式桥模式 - 以简单易用的步骤学习java设计模式:初学者教程,包含从工厂模式,抽象工厂,单例,构建器,原型,适配器,桥,过滤器,复合,装饰器开始的java设计模式的完整知识外立面,Flyweight,代理,命令,口译员,迭代器,调解员,纪念品,观察员,状态,空对象,战略,模板,访客,MVC,前端控制器等。

当我们需要将抽象与其实现分离时使用Bridge,以便两者可以独立变化.这种类型的设计模式属于结构模式,因为这种模式通过在它们之间提供桥接结构来解耦实现类和抽象类.

这种模式涉及一个充当桥梁的接口,具体类的功能独立于接口实现者类.两种类型的类都可以在结构上进行修改而不会相互影响.

我们通过以下示例演示Bridge模式的使用,其中可以使用相同的抽象类方法以不同的颜色绘制圆形但是不同的桥梁实施者类.

实现

我们有一个 DrawAPI 接口,它充当桥接器实现者和具体类 RedCircle GreenCircle 实现 DrawAPI 接口. Shape 是一个抽象类,将使用 DrawAPI 的对象. BridgePatternDemo ,我们的演示类将使用 Shape 类绘制不同颜色的圆圈.

Bridge Pattern UML Diagram

Step 1

创建桥接器实现接口.

DrawAPI.java

public interface DrawAPI {   public void drawCircle(int radius, int x, int y); }

步骤2

创建实现 DrawAPI  interface.

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 + "]");   }}

第3步

创建抽象类 Shape 使用 DrawAPI 界面.

Shape.java

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;   }   public void draw() {      drawAPI.drawCircle(radius,x,y);   } }

第5步

使用形状 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();   } }

步骤6

验证输出.

Drawing Circle[ color: red, radius: 10, x: 100, 100]Drawing Circle[  color: green, radius: 10, x: 100, 100]