设计模式9-桥接模式

1. 概念

桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立变化,而不会相互影响。桥接模式通过组合的方式,将多个维度的变化分离开来,从而提高系统的灵活性和可扩展性。

在桥接模式中,主要包含以下角色:

  1. 抽象部分(Abstraction):定义抽象类接口,它维护一个指向实现部分的引用对象,并定义了基于实现部分的高级操作。

  2. 扩展抽象部分(Refined Abstraction):继承自抽象部分,扩展了抽象部分的接口,可以实现更复杂的业务逻辑。

  3. 实现部分接口(Implementor):定义实现部分的接口,该接口不一定与抽象部分完全一致,但是通常提供基本的操作方法供具体实现类实现。

  4. 具体实现部分(Concrete Implementor):实现部分接口的具体实现类,提供具体的业务逻辑。

桥接模式的关键在于将抽象部分和实现部分分离,使得它们可以独立变化。通过这种方式,我们可以在不修改原有代码的情况下,动态地替换抽象部分或实现部分的具体实现,从而灵活地应对需求变化和系统扩展。

2. 示例

// 实现部分的接口
interface DrawingAPI {
    void drawCircle(int x, int y, int radius);
}

// 具体实现部分:画图API A
class DrawingAPIA implements DrawingAPI {
    public void drawCircle(int x, int y, int radius) {
        System.out.printf("API A - Drawing circle at (%d:%d) with radius %d\n", x, y, radius);
    }
}

// 具体实现部分:画图API B
class DrawingAPIB implements DrawingAPI {
    public void drawCircle(int x, int y, int radius) {
        System.out.printf("API B - Drawing circle at (%d:%d) with radius %d\n", x, y, radius);
    }
}

// 抽象部分
abstract class Shape {
    protected DrawingAPI drawingAPI;

    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }

    public abstract void draw();
}

// 扩展抽象部分:圆形
class Circle extends Shape {
    private int x, y, radius;

    public Circle(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 BridgePatternExample {
    public static void main(String[] args) {
        DrawingAPI apiA = new DrawingAPIA();
        DrawingAPI apiB = new DrawingAPIB();

        Shape circle1 = new Circle(1, 2, 3, apiA);
        circle1.draw();  // 输出:API A - Drawing circle at (1:2) with radius 3

        Shape circle2 = new Circle(5, 7, 10, apiB);
        circle2.draw();  // 输出:API B - Drawing circle at (5:7) with radius 10
    }
}

在这个示例中,DrawingAPI 定义了画图的接口,DrawingAPIADrawingAPIB 分别是不同的画图实现。Shape 是抽象部分,Circle 是扩展抽象部分,它们可以基于不同的 DrawingAPI 实现画图的功能。这样,我们可以动态地将 Circle 对象关联到不同的 DrawingAPI 上,实现了抽象部分和实现部分的解耦。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值