网站建设要咨询哪些,长沙网站外包公司吗,免费网站入口,新网站不被收录对象的继承关系是在编译时就定义好了#xff0c;所以无法在运行时改变从父类继承的实现。子类的实现与它的父类有非常紧密的依赖关系#xff0c;以至于父类实现中的任何变化必然会导致子类发生变化。当你需要复用子类时#xff0c;如果继承下来的实现不适合解决新的问题所以无法在运行时改变从父类继承的实现。子类的实现与它的父类有非常紧密的依赖关系以至于父类实现中的任何变化必然会导致子类发生变化。当你需要复用子类时如果继承下来的实现不适合解决新的问题则父类必须重写或被其他更适合的类替换。这种依赖顾关系限制了灵活性并最终限制了复用性[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_HAbstractionImp.cpp
#include iostream
#include AbstractionImp.husing 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.hclass 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_HAbstraction.cpp
#include abstraction.hAbstraction::~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.husing namespace std;int main() {AbstractionImp *imp new ConcretetAbstractionImpA();Abstraction *abs new RefinedAbstraction(imp);abs-Operation();return 0;
}