Charpter19 组合模式

组合模式简介

组合模式(Composite),将对象组合成树形结构以表示‘‘部分-整体’的层次结构。组合模式使得用户对于单个对象和组合对象的使用具有一致性。

组合模式UML类图

Charpter19 组合模式

 

 

C++代码实现

// Component类
#ifndef _COMPONENT_HPP
#define _COMPONENT_HPP
#include<string>
using namespace std;

class Component{
public:
    Component(string name):name(name){

    }
    virtual void add(Component* c) { };
    virtual void remove(Component* c) { };
    virtual void display(int n) {};
protected:
    string name;
};

#endif
// Leaf类
#ifndef _LEAF_HPP
#define _LEAF_HPP

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

class Leaf : public Component{
public:
    Leaf(string name) : Component(name) {

    }
    virtual void add(Component* c){
        cout << "cant't add() in Leaf" << endl;
    }
    virtual void remove(Component* c) {
        cout << "can't remove() in Leaf" << endl;
    }   
    virtual void display(int n){
        for(int i = 0; i < n; ++i){
            cout << '-';
        }
        cout << name << endl;
    }
    
};

#endif
// Composite类
#ifndef _COMPOSITE_HPP
#define _COMPOSITE_HPP

#include<iostream>
#include<string>
#include<list>
#include"component.hpp"

using namespace std;

class Composite:public Component{
public:
    Composite(string name):Component(name){

    }

    virtual void add(Component*c) override {
        l.push_back(c);
    }

    virtual void remove(Component*c) override {
        l.pop_back();
    }

    virtual void display(int n) override {
        for(int i = 0; i < n; ++i){
            cout << '-';
        }
        cout << name <<endl;       
        for(auto i : l) {
            i->display( n+4 ); 
        }  
    }

private:
    list<Component*> l;
};

#endif
// 客户端程序
#include<iostream>
#include"composite.hpp"
#include"leaf.hpp"

using namespace std;

int main(){
    Composite* root = new Composite("root");
    root->add(new Leaf("LeafA"));
    root->add(new Leaf("LeafB"));
    
    Composite* comp = new Composite("CompositeX");
    comp->add(new Leaf("XA"));
    comp->add(new Leaf("XB"));

    root->add(comp);

    Composite* comp2 = new Composite("CompositeXX");
    comp2->add(new Leaf("XXA"));
    comp2->add(new Leaf("XXB"));

    comp->add(comp2);

    root -> add(new Leaf("LeafC"));
    root -> add(new Leaf("LeafC"));

    root->display(1);
    getchar();
    return 0;
}

运行结果:

Charpter19 组合模式

 

上一篇:多版本并发控制 MVCC简介


下一篇:软件使用体验