设计模式7之c++桥接模式(示例代码)

桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分和实现部分分离,使它们可以独立地变化,并在它们之间建立一个桥接连接。这种模式使用了“组合优于继承”的原则,将系统中的多个维度进行组合,以满足不同的需求。

以下是C++桥接模式的示例代码:

#include <iostream>
using namespace std;

// 实现部分
class Implementor {
public:
    virtual void operation() = 0;
};
class ConcreteImplementorA : public Implementor {
public:
    void operation() {
        cout << "ConcreteImplementorA operation" << endl;
    }
};
class ConcreteImplementorB : public Implementor {
public:
    void operation() {
        cout << "ConcreteImplementorB operation" << endl;
    }
};

// 抽象部分
class Abstraction {
protected:
    Implementor* implementor;
public:
    virtual void operation() = 0;
};
class RefinedAbstraction : public Abstraction {
public:
    RefinedAbstraction(Implementor* impl) {
        implementor = impl;
    }
    void operation() {
        implementor->operation();
    }
};

// 客户端
int main() {
    Implementor* implementorA = new ConcreteImplementorA();
    Abstraction* abstractionA = new RefinedAbstraction(implementorA);
    abstractionA->operation();
    Implementor* implementorB = new ConcreteImplementorB();
    Abstraction* abstractionB = new RefinedAbstraction(implementorB);
    abstractionB->operation();
    return 0;
}

以上代码定义了Implementor接口,ConcreteImplementorA和ConcreteImplementorB分别实现了该接口。Abstraction是抽象部分,RefinedAbstraction是具体部分,它们都持有一个Implementor的实例。客户端可以通过实例化不同的Implementor对象并传递给RefinedAbstraction来实现不同的行为。

优点:

  • 通过将实现部分和抽象部分分离,桥接模式可以让它们各自独立地进行修改,从而降低系统的耦合度。
  • 桥接模式可以提高系统的可扩展性,因为它可以让新的抽象部分和实现部分相互组合,产生新的行为。
  • 桥接模式可以让实现部分和抽象部分分别进行继承,从而避免了多层继承的复杂性。

缺点:

  • 桥接模式会增加代码的复杂度,因为它需要定义多个类来实现一个功能。
  • 桥接模式可能会导致系统中类的数量增加,增加了系统的维护成本。
  • 桥接模式需要客户端知道不同的实现部分,从而增加了客户端的复杂度。

总之,桥接模式适用于抽象和实现部分的变化频繁,且需要独立变化的场景。但是在系统较小或实现部分和抽象部分不会发生变化的情况下,使用桥接模式可能会增加代码的复杂度,不建议使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值