当我们需要将抽象与其实现分离时使用Bridge,以便两者可以独立变化.这种类型的设计模式属于结构模式,因为这种模式通过在它们之间提供桥接结构来解耦实现类和抽象类.
这种模式涉及一个充当桥梁的接口,具体类的功能独立于接口实现者类.两种类型的类都可以在结构上进行修改而不会相互影响.
我们通过以下示例演示Bridge模式的使用,其中可以使用相同的抽象类方法以不同的颜色绘制圆形但是不同的桥梁实施者类.
我们有一个 DrawAPI 接口,它充当桥接器实现者和具体类 RedCircle , GreenCircle 实现 DrawAPI 接口. Shape 是一个抽象类,将使用 DrawAPI 的对象. BridgePatternDemo ,我们的演示类将使用 Shape 类绘制不同颜色的圆圈.
创建桥接器实现接口.
DrawAPI.java
public interface DrawAPI { public void drawCircle(int radius, int x, int y); }
创建实现 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 + "]"); } }
创建抽象类 Shape 使用 DrawAPI 界面.
Shape.java
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); }
创建实现 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); } }
使用形状和 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(); } }
验证输出.
Drawing Circle[ color: red, radius: 10, x: 100, 100] Drawing Circle[ color: green, radius: 10, x: 100, 100]