首页 > 其他 > 详细

Charpter19 组合模式

时间:2020-03-28 22:06:19      阅读:66      评论:0      收藏:0      [点我收藏+]

组合模式简介

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

组合模式UML类图

技术分享图片

 

 

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 组合模式

原文:https://www.cnblogs.com/yb-blogs/p/12589716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!