桥接模式的Java项目实例
时间: 2023-09-23 14:07:15 浏览: 45
很高兴为您提供有关桥接模式的Java项目实例。桥接模式是一种结构性设计模式,可用于将抽象与实现解耦。
以下是一个简单的桥接模式的Java项目实例:
1.先定义一个 Shape 接口和一个 Drawing 接口,如下所示:
```java
public interface Shape {
public void draw();
}
public interface Drawing {
public void drawCircle(int x, int y, int radius);
public void drawRectangle(int x1, int y1, int x2, int y2);
}
```
2.然后实现具体的 Shape 类和 Drawing 类,如下所示:
```java
public class CircleShape implements Shape {
private int x, y, radius;
private Drawing drawing;
public CircleShape(int x, int y, int radius, Drawing drawing) {
this.x = x;
this.y = y;
this.radius = radius;
this.drawing = drawing;
}
public void draw() {
drawing.drawCircle(x, y, radius);
}
}
public class RectangleShape implements Shape {
private int x1, y1, x2, y2;
private Drawing drawing;
public RectangleShape(int x1, int y1, int x2, int y2, Drawing drawing) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.drawing = drawing;
}
public void draw() {
drawing.drawRectangle(x1, y1, x2, y2);
}
}
public class DrawingImpl implements Drawing {
public void drawCircle(int x, int y, int radius) {
System.out.println("Drawing circle at (" + x + ", " + y + ") with radius " + radius);
}
public void drawRectangle(int x1, int y1, int x2, int y2) {
System.out.println("Drawing rectangle from (" + x1 + ", " + y1 + ") to (" + x2 + ", " + y2 + ")");
}
}
```
3.最后,我们可以使用这些类来画出不同的形状,如下所示:
```java
public static void main(String[] args) {
Drawing drawing = new DrawingImpl();
Shape circle = new CircleShape(10, 10, 5, drawing);
circle.draw();
Shape rectangle = new RectangleShape(20, 20, 30, 30, drawing);
rectangle.draw();
}
```
这是一个简单的桥接模式的Java项目实例。它演示了如何将抽象和实现分离,使得它们可以独立进行扩展。当我们需要添加新的形状或绘图方式时,只需要实现相应的类即可,而不用改变现有类的代码。