桥接模式C++

合成/聚合复用原则

合成/聚合复用原则(CARP):尽量使用合成/聚合,尽量不用使用类继承(这是一种强耦合)。优先使用对象的合成/聚合有助于保持每个类被封装,并被集中在单个任务上,这样类和类继承层次会保持比较小的规模,并且不大可能增长为不可控制的庞然大物。

桥接模式

桥接模式,将抽象部分与它的实现部分分离,使它们都可以独立地变化。这里实现指的是抽象类和它的派生类用来实现自己的对象,也就是说实现系统可能有多角度分类,每一个分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

桥接模式结构图

桥接模式C++_第1张图片
image

桥接模式基本代码

#include 
using namespace std;

class Implementor {
public:
    virtual void Operation() = 0;
    virtual ~Implementor(){}
};

class ConcreteImplementorA : public Implementor{
public:
    void Operation() {
        cout << "ConcreteImplementorA" << endl;
    }
};

class ConcreteImplementorB : public Implementor{
public:
    void Operation() {
        cout << "ConcreteImplementorB" << endl;
    }
};

class Abstraction {
protected:
    Implementor* implementor;
public:
    void setImplementor(Implementor* im) {
        implementor = im;
    }
    virtual void Operation() {
        implementor->Operation();
    }
    virtual ~Abstraction(){}
};

class RefinedAbstraction : public Abstraction{
public:
    void Operation() {
        implementor->Operation();
    }
};

int main() {
    Abstraction* r = new RefinedAbstraction();
    ConcreteImplementorA* ca = new ConcreteImplementorA();
    ConcreteImplementorB* cb = new ConcreteImplementorB();
    r->setImplementor(ca);
    r->Operation();
    r->setImplementor(cb);
    r->Operation();

    delete ca;
    delete cb;
    delete r;
    return 0;
}

你可能感兴趣的:(桥接模式C++)