给我写一个运用了桥接适配器模式的Java项目,要有具体的代码

2023-04-07by@1505049272-BLKch&@ChatGPT.Model: gpt-3.5
1505049272-BLKch

给我写一个运用了桥接适配器模式的Java项目,要有具体的代码

Avatar
Avatar

以下是一个简单的例子,演示如何使用桥接适配器模式:

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
1505049272-BLKch

它的哪个部分是适配器

Avatar
Avatar

在这个例子中,桥接适配器模式的适配器部分是DrawAPI接口和RedCircleGreenRectangle类的实现。这些类通过实现DrawAPI接口,将CircleRectangle对象与具体的绘图API(即RedCircleGreenRectangle)进行适配,使得它们可以使用绘图API的方法来完成具体的绘图操作。这样,CircleRectangle对象可以通过调用适配器的方法实现不同的绘制方式,而不需要了解具体的绘图API实现。

1505049272-BLKch

画出它的uml图

Avatar
Avatar

下面是桥接适配器模式的UML类图:

Bridge Adapter Pattern UML Diagram

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