Dotcpp  >  编程教程  >  结构型模式(Structural Patterns)  >  桥接模式

桥接模式

点击打开在线编译器,边学边练

桥接模式是一种结构型设计模式,它的主要目的是将抽象和实现分离,使它们可以独立地变化。桥接模式通过使用组合关系来连接抽象和实现,而不是继承。

在实际应用中,桥接模式非常适用于多维度变化的场景。它可以解耦抽象和实现,使它们可以独立地扩展和演化。同时,桥接模式还可以简化类的继承关系,减少子类的数量。

在桥接模式中,有两个关键角色:
1. Abstraction(抽象类):它定义了对客户端的抽象接口,并包含一个对实现类的引用。它通常提供一些高级操作,而这些操作由实现类来实现。
2. Implementor(实现类接口):它定义了对实现的抽象接口。实现类接口通常提供一些基本操作的接口,而这些接口由具体的实现类来具体实现。

桥接模式

下面是一个简单的Java示例,展示了如何使用桥接模式:

// Implementor interface
public interface DrawingAPI {
    void drawCircle(int x, int y, int radius);
}
// Concrete Implementor 1
public class DrawingAPI1 implements DrawingAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("API1.circle at " + x + ":" + y + " radius " + radius);
    }
}
// Concrete Implementor 2
public class DrawingAPI2 implements DrawingAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("API2.circle at " + x + ":" + y + " radius " + radius);
    }
}
// Abstraction
public abstract class Shape {
    protected DrawingAPI drawingAPI;
    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }
    public abstract void draw();
}
// Refined Abstraction
public class CircleShape extends Shape {
    private int x, y, radius;
    public CircleShape(int x, int y, int radius, DrawingAPI drawingAPI) {
        super(drawingAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    @Override
    public void draw() {
        drawingAPI.drawCircle(x, y, radius);
    }
}
public class BridgePatternDemo {
    public static void main(String[] args) {
        Shape circle1 = new CircleShape(1, 2, 3, new DrawingAPI1());
        Shape circle2 = new CircleShape(4, 5, 6, new DrawingAPI2());
        circle1.draw();
        circle2.draw();
    }
}

在这个示例中,DrawingAPI接口定义了一个绘制圆的方法。DrawingAPI1和DrawingAPI2是具体的实现类,它们实现了绘制圆的具体逻辑。

Shape类是抽象类,它包含一个对DrawingAPI的引用,并提供了一个抽象的draw()方法。CircleShape是Shape的具体子类,它实现了draw()方法,并调用了DrawingAPI来绘制具体的图形。

通过使用桥接模式,我们可以将抽象和实现分离,可以灵活地扩展和演化。这使得我们可以根据不同的需求来定制具体的实现,而不必修改大量的代码。


本文固定URL:https://www.dotcpp.com/course/1365

上一课:

适配器模式

下一课:

过滤器模式

Dotcpp在线编译      (登录可减少运行等待时间)