java 桥接模式 例子
时间: 2023-05-20 14:00:47 浏览: 110
桥接模式是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。下面是一个 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("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", y: " + y + "]");
}
}
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 + "]");
}
}
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();
}
}
```
这个例子中,`DrawAPI` 接口定义了一个画圆的方法,`RedCircle` 和 `GreenCircle` 类实现了这个接口并分别实现了不同颜色的圆的绘制。`Shape` 抽象类定义了一个 `DrawAPI` 对象,表示一个形状,它的子类 `Circle` 实现了 `draw()` 方法,调用 `DrawAPI` 对象的 `drawCircle()` 方法来绘制圆。在 `BridgePatternDemo` 类中,我们创建了一个红色圆和一个绿色圆,并分别调用它们的 `draw()` 方法来绘制圆。
阅读全文