ڼС
梦回起点
做你害怕做的事,你会发现:不过如此
本站基于WordPress—主题by 设计窝
冀ICP备15003737号
梦回起点
Copyright © 2015-2024 All rights reserved.

组合模式——大话设计模式读书笔记

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

下面是组合模式的UML图:

组合模式

下面是C++实现的代码:

/*
 * Copyright (c) 2017 initm.com All rights reserved.
 * 作者: Stupid
 * 描述: 组合模式
 * 完成时间: 2017-11-3 23:17
*/

#include <QCoreApplication>
#include <iostream>
#include <string>
#include <list>

class Component
{
protected:
    std::string name;
public:
    Component(std::string name):name(name){}
    virtual void Add(Component*const& c) = 0;
    virtual void Remove(Component*const& c) = 0;
    virtual void Display(int depth) = 0;
    virtual ~Component(){}
};

class Leaf: public Component
{
public:
    Leaf(std::string name): Component(name){}
    ~Leaf(){}
    void Add(Component*const&)override final{
        std::cout << "Cannot add to a leaf" << std::endl;
    }
    void Remove(Component*const&)override final{
        std::cout << "Cannot remove to a leaf" << std::endl;
    }
    void Display(int depth)override final{
        std::cout << std::string(depth, '-');
        std::cout << this->name << std::endl;
    }
};

class Composite: public Component
{
private:
    std::list<Component*> children;
public:
    Composite(std::string name):Component(name){}
    ~Composite(){
        for (auto it = children.begin(); it != children.end(); it = children.erase(it)){
            delete *it;
            *it = nullptr;
        }
    }
    void Add(Component*const& c)override final{
        children.push_back(c);
    }
    void Remove(Component*const& c)override final{
        children.remove(c);
        delete c;
    }
    void Display(int depth)override final{
        std::cout << std::string(depth, '-');
        std::cout << this->name << std::endl;
        for (auto index: children){
            index->Display(depth + 2);
        }
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Composite* root = new Composite("root");

    root->Add( new Leaf("Leaf A"));
    root->Add( new Leaf("Leaf B"));

    Composite* comp = new Composite("Composite X");
    comp->Add(new Leaf("Leaf XA"));
    comp->Add(new Leaf("Leaf XB"));

    root->Add(comp);

    Composite* comp2 = new Composite("Composite XY");
    comp2->Add(new Leaf("Leaf XYA"));
    comp2->Add(new Leaf("Leaf XYB"));

    comp->Add(comp2);

    root->Add(new Leaf("Leaf C"));

    Leaf* leaf = new Leaf("Leaf D");
    root->Add(leaf);
    root->Remove(leaf);

    root->Display(1);

    return a.exec();
}

组合模式使得用户不用关心是叶子节点还是一个组合组件。

2017-11-03
                         
暂无评论

发表回复