实例
我们有一个DrawAPI接口,它充当桥实现者,而具体类RedCircle和GreenCircle实现了DrawAPI接口。Shape是一个抽象类,将使用DrawAPI的对象。BridgePatternDemo,我们的演示类将使用Shape类绘制不同的彩色圆圈。
第1步 - 创建网桥实现者接口。DrawAPI.java
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
第2步 - 创建实现DrawAPI接口的具体网桥实现程序类。 RedCircle.java , GreenCircle.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 + "]");
}
}
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。 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步 - 使用Shape和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]