桥接模式
对象的继承关系是在编译时就定义好了,所以无法在运行时改变从父类继承的实现。子类的实现与它的父类有非常紧密的依赖关系,以至于父类实现中的任何变化必然会导致子类发生变化。当你需要复用子类时,如果继承下来的实现不适合解决新的问题,则父类必须重写或被其他更适合的类替换。这种依赖顾关系限制了灵活性并最终限制了复用性[DP]。
合成/聚合复用原则(CARP),尽量使用合成/集合,尽量不要使用类继承。
**桥接模式(Bridge):**将抽象部分与它的实现部分分离,使它们都可以独立地变化。
AbstractionImp.h
#ifndef ABSTRACTIONIMP_H
#define ABSTRACTIONIMP_Hclass AbstractionImp {
public:virtual ~AbstractionImp() = default;virtual void Operation();AbstractionImp() = default;
};class ConcretetAbstractionImpA : public AbstractionImp {
public:ConcretetAbstractionImpA() = default;~ConcretetAbstractionImpA() override = default;void Operation() override;
};class ConcretetAbstractionImpB : public AbstractionImp {
public:ConcretetAbstractionImpB() = default;~ConcretetAbstractionImpB() override = default;void Operation() override;
};#endif //ABSTRACTIONIMP_H
AbstractionImp.cpp
#include <iostream>
#include "AbstractionImp.h"using namespace std;void AbstractionImp::Operation() {cout << "AbstractionImp....imp..." << endl;
}void ConcretetAbstractionImpA::Operation() {cout << "ConcreteAbstractionImpA...." << endl;
}void ConcretetAbstractionImpB::Operation() {cout << "ConcreteAbstractionImpB...." << endl;
}
Abstraction.h
#ifndef ABSTRACTION_H
#define ABSTRACTION_H#include "AbstractionImp.h"class Abstraction {
public:virtual ~Abstraction();virtual void Operation() = 0;
protected:Abstraction();
};class RefinedAbstraction : public Abstraction {
public:explicit RefinedAbstraction(AbstractionImp *imp);~RefinedAbstraction() override;void Operation() override;
protected:AbstractionImp *_imp;
};
#endif //ABSTRACTION_H
Abstraction.cpp
#include "abstraction.h"Abstraction::~Abstraction() = default;Abstraction::Abstraction() = default;RefinedAbstraction::RefinedAbstraction(AbstractionImp *imp) {_imp = imp;
}RefinedAbstraction::~RefinedAbstraction() = default;void RefinedAbstraction::Operation() {_imp->Operation();
}
main.cpp
#include <iostream>
#include "Abstraction.h"
#include "AbstractionImp.h"using namespace std;int main() {AbstractionImp *imp = new ConcretetAbstractionImpA();Abstraction *abs = new RefinedAbstraction(imp);abs->Operation();return 0;
}