给我写一个运用了桥接适配器模式的Java项目,要有具体的代码
以下是一个简单的例子,演示如何使用桥接适配器模式:
Shape.java
public interface Shape {
void draw();
}
Circle.java
public class Circle implements Shape {
private final int x, y, radius;
private final DrawAPI drawAPI;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
this.x = x;
this.y = y;
this.radius = radius;
this.drawAPI = drawAPI;
}
@Override
public void draw() {
drawAPI.drawCircle(x, y, radius);
}
}
Rectangle.java
public class Rectangle implements Shape {
private final int x, y, width, height;
private final DrawAPI drawAPI;
public Rectangle(int x, int y, int width, int height, DrawAPI drawAPI) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.drawAPI = drawAPI;
}
@Override
public void draw() {
drawAPI.drawRectangle(x, y, width, height);
}
}
DrawAPI.java
public interface DrawAPI {
void drawCircle(int x, int y, int radius);
void drawRectangle(int x, int y, int width, int height);
}
RedCircle.java
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int x, int y, int radius) {
System.out.println("Drawing red circle at (" + x + ", " + y + "), radius " + radius);
}
@Override
public void drawRectangle(int x, int y, int width, int height) {
// do nothing
}
}
GreenRectangle.java
public class GreenRectangle implements DrawAPI {
@Override
public void drawCircle(int x, int y, int radius) {
// do nothing
}
@Override
public void drawRectangle(int x, int y, int width, int height) {
System.out.println("Drawing green rectangle at (" + x + ", " + y + "), width " + width + ", height " + height);
}
}
BridgeAdapterDemo.java
public class BridgeAdapterDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 50, new RedCircle());
redCircle.draw();
Shape greenRectangle = new Rectangle(200, 200, 100, 50, new GreenRectangle());
greenRectangle.draw();
}
}
输出:
Drawing red circle at (100, 100), radius 50
Drawing green rectangle at (200, 200), width 100, height 50
它的哪个部分是适配器
在这个例子中,桥接适配器模式的适配器部分是DrawAPI接口和RedCircle、GreenRectangle类的实现。这些类通过实现DrawAPI接口,将Circle和Rectangle对象与具体的绘图API(即RedCircle和GreenRectangle)进行适配,使得它们可以使用绘图API的方法来完成具体的绘图操作。这样,Circle和Rectangle对象可以通过调用适配器的方法实现不同的绘制方式,而不需要了解具体的绘图API实现。
画出它的uml图
下面是桥接适配器模式的UML类图:

在此类图中,Shape是抽象类或接口,表示不同的图形形状。Circle和Rectangle是实现Shape的具体类,它们包含了一个指向DrawAPI接口的引用,以便将绘图操作委托给具体的绘图API类。DrawAPI是一个接口,表示绘图API的方法。RedCircle和GreenRectangle是实现DrawAPI接口的具体类,它们实现了绘制不同形状和颜色的图形。BridgeAdapterDemo类是一个简单的客户端,演示如何使用桥接适配器模式。