Chapter22 合成/聚合复用原则及桥接模式

合成/聚合复用原则简介

合成/聚合复用原则(CARP),尽量使用合成/聚合,尽量不要使用类的继承。

合成(Composition)聚合(Aggregation)都是关联的特殊种类。聚合表示一种弱的‘拥有’关系,体现的是A对象可以包含B对象,但B对象不是A对象的一部分;合成则是一种强的‘拥有’关心,体现了严格的部分与整体的关系,部分和整体的声明周期一样。

“合成/聚合复用原则的好处是,优先使用对象的合成/聚合将有助于你保持每个类被封装,并被集中在单个任务上,这样类和类继承层次会保持较小的规模,并且不太可能增长为不可控制的庞然大物”

桥接模式简介

桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。

抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。

实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

桥接模式UML类图

 

 

C++代码实现

// Implementor类
#ifndef _IMPLEMENTOR_HPP
#define _IMPLEMENTOR_HPP
class Implementor{
public:
    virtual void operationImp() = 0;
};

#endif
// Abstraction类
#ifndef _ABSTRACTION_HPP
#define _ABSTRACTION_HPP

#include"implementor.hpp"

class Abstraction{
public:
    virtual void myOperation() = 0;
protected:
    Implementor* imp;    
};

#endif
// ConcreteImplementA类
#ifndef _CONCRETEIMPLEMENTORA_HPP
#define _CONCRETEIMPLEMENTORA_HPP

#include<iostream>
#include"implementor.hpp"
using namespace std;

class ConcreteImplementorA : public Implementor{
public:
    virtual void operationImp() override {
        cout << "this is operationImp from A" <<endl;
    }
};

#endif
// ConcreteImplementB类
#ifndef _CONCRETEIMPLEMENTORB_HPP
#define _CONCRETEIMPLEMENTORB_HPP

#include<iostream>
#include"implementor.hpp"
using namespace std;

class ConcreteImplementorB : public Implementor{
public:
    virtual void operationImp() override {
        cout << "this is operationImp from B" <<endl;
    }
};

#endif
// RefinedAbstraction类
#ifndef _REFINEDABSTRACTION_HPP
#define _REFINEDABSTRACTION_HPP

#include"abstraction.hpp"
#include"implementor.hpp"

using namespace std;

class RefinedAbstraction: public Abstraction{
public:
    RefinedAbstraction(Implementor* impl){
        imp = impl;
    }

    virtual void myOperation()override{
        imp->operationImp();
    }

};

#endif
//客户端代码
#include<iostream>

#include"concreteimplementora.hpp"
#include"concreteimplementorb.hpp"
#include"refinedabstraction.hpp"

using namespace std;
int main(){
    ConcreteImplementorA* impA = new ConcreteImplementorA();
    ConcreteImplementorB* impB = new ConcreteImplementorB();
    RefinedAbstraction* refinedAbsA = new RefinedAbstraction(impA);
    refinedAbsA->myOperation();

    RefinedAbstraction* refinedAbsB = new RefinedAbstraction(impB);
    refinedAbsB->myOperation();

    getchar();
    return 0;
}

运行结果:

 

posted @ 2020-03-31 11:02  yangbofun  阅读(175)  评论(0)    收藏  举报