大话设计模式之桥接模式

发布于:2024-04-11 ⋅ 阅读:(174) ⋅ 点赞:(0)

桥接模式是一种结构型设计模式,它将抽象部分与它的实现部分分离,使它们可以独立地变化。这种模式通过提供一个桥接接口来实现这种分离,使得抽象部分和实现部分可以在运行时独立地进行修改。

桥接模式主要由两个部分组成:抽象部分和实现部分。

  • 抽象部分(Abstraction):定义了抽象类或接口,并包含一个对实现部分的引用。
  • 实现部分(Implementor):定义了实现类或接口,与抽象部分相互配合,完成功能。
#include <iostream>

// 实现部分接口
class Implementor {
public:
    virtual void operationImpl() const = 0;
};

// 具体实现部分A
class ConcreteImplementorA : public Implementor {
public:
    void operationImpl() const override {
        std::cout << "Concrete Implementor A operation" << std::endl;
    }
};

// 具体实现部分B
class ConcreteImplementorB : public Implementor {
public:
    void operationImpl() const override {
        std::cout << "Concrete Implementor B operation" << std::endl;
    }
};

// 抽象部分
class Abstraction {
protected:
    Implementor* implementor_;

public:
    Abstraction(Implementor* implementor) : implementor_(implementor) {}

    virtual void operation() const = 0;
};

// 具体抽象部分
class RefinedAbstraction : public Abstraction {
public:
    RefinedAbstraction(Implementor* implementor) : Abstraction(implementor) {}

    void operation() const override {
        std::cout << "Refined Abstraction operation" << std::endl;
        implementor_->operationImpl();
    }
};

int main() {
    // 创建具体实现部分对象
    ConcreteImplementorA implementorA;
    ConcreteImplementorB implementorB;

    // 使用不同的实现部分创建具体抽象部分对象
    RefinedAbstraction abstractionA(&implementorA);
    RefinedAbstraction abstractionB(&implementorB);

    // 调用抽象部分的操作方法
    abstractionA.operation();
    abstractionB.operation();

    return 0;
}

/*
在这个示例中,Implementor 是实现部分的接口,定义了实现部分的操作方法。
ConcreteImplementorA 和 ConcreteImplementorB 是具体实现部分,
分别实现了 Implementor 接口。Abstraction 是抽象部分的接口,包含一个对实现部分的引用。
RefinedAbstraction 是具体抽象部分,实现了抽象部分的操作方法,并调用了实现部分的方法。

在 main() 函数中,我们创建了具体的实现部分对象和抽象部分对象,并调用了抽象部分的操作方法,
实现了桥接模式的功能。
*/

觉得有帮助的话,打赏一下呗。。

           


网站公告

今日签到

点亮在社区的每一天
去签到