Java中桥接模式的代码示例
时间: 2023-09-23 08:06:48 浏览: 44
当然,这是一个常见的设计模式,Java中实现桥接模式的代码示例如下:
```
interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
class RedCircle implements DrawAPI {
public void drawCircle(int radius, int x, int y) {
System.out.println("画红色圆形,半径为 " + radius + ", x 坐标为 " + x + ", y 坐标为 " + y);
}
}
class GreenCircle implements DrawAPI {
public void drawCircle(int radius, int x, int y) {
System.out.println("画绿色圆形,半径为 " + radius + ", x 坐标为 " + x + ", y 坐标为 " + y);
}
}
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
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);
}
}
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();
}
}
```
这个示例演示了一个银行展示的可能性。在这种情况下,被称为“对象”和“product”提供的不同角色中,Shape是“抽象的对象”,而DrawAPI是使用在“实现的对象”中。 BridgePatternDemo类是使用Shape和DrawAPI类的示例。 通过使用具有通用接口的导管,以及在运行时根据需要替换导管,Bridge模式将两个实体分开,因此可以相互独立地进行修改。