码迷,mamicode.com
首页 > 其他好文 > 详细

浅谈设计模式之七——Composite模式

时间:2015-04-28 23:03:34      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:设计模式   组合   模板   composite   

同样地,先上uml图:
技术分享
组合模式的意图:将对象组合合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
uml解析:leaf是叶节点,Composite可以理解为是一个多个叶节点的组合,它是非叶节点,就相当于一个元件以及一个元件容器,里面有很多元件一样。这里可以用list或者vector实现。
本来是想用模板来实现,后来发现实在是多此一举,而且反而更不好了。
这里需要说的一点就是Leaf是叶节点,因此肯定没有添加、删除等功能,因为这些是没有意义的,这一点也是组合模式需要考虑的问题吧,这样会使得操作Leaf跟Composite会有少许的不同。
下面给出可执行代码:
Composition.h

#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

/*template<typename T>*/
class Component
{
public:
    Component(void);
    virtual ~Component(void);

public:
    virtual void Display() = 0;
    virtual void Add(Component &leaf){}
    virtual bool Remove(Component &leaf){return false;}
    virtual Component * GetChild(int Index)=0;
protected:
    std::string m_string;

};


class Composite:public Component
{
public:
    Composite(){}
    ~Composite(){}
    void Display();
    void Add(Component &leaf);
    bool Remove(Component &leaf);
    Component* GetChild(int Index);
private:
    vector<Component *> m_Com;
};

// template<typename T>
class Leaf:public Component
{
public:
    Leaf(std::string & str);
    Leaf(){}
    void Display();
//  bool Add(Leaf &leaf){}
//  bool Remove(){}
    Component* GetChild(int Index){ return NULL;}
private:
    std::string mstring;
};

Composition.cpp

#include "Component.h"

Component::Component()
{
}

Component::~Component()
{
}

void Composite::Add(Component &leaf) 
{
    m_Com.push_back(&leaf);
}

/*template<typename T>*/
bool Composite::Remove(Component &leaf)
{

    vector<Component *>::iterator itor=find(m_Com.begin(),m_Com.end(),&leaf);
    if (itor == m_Com.end())
    {
        return false;
    }
    else
    {
        m_Com.erase(itor);
        return true;
    }   
}

Component * Composite::GetChild(int Index)
{
    return m_Com[Index];
};

void Composite::Display()
{
    vector<Component*>::iterator itor = m_Com.begin();
    for (;itor!=m_Com.end();itor++)
    {
        (*itor)->Display();
    }
}

Leaf::Leaf(std::string &str):mstring(str)
{
}

// template<typename T>
void Leaf::Display()
{
    cout<<mstring<<endl;
}

main.cpp

#include "Component.h"

int main(int argc,char **argv)
{
    std::string str1="Leaf1";
    std::string str2="Leaf2";
    std::string str3="Leaf3";
    Leaf leaf1(str1);
    Leaf leaf2(str2);
    Leaf leaf3(str3);

    Component *f = new Composite;
    f->Add(leaf1);
    f->Add(leaf2);
    f->Add(leaf3);

    f->Display();

    f->Remove(leaf2);
    f->Display();

    return 0;
}

执行之后的结果:
技术分享

一开始显示Leaf1、Leaf2、Leaf3,删除之后显示Leaf1、Leaf3。
这就是组合模式,祝读者生活快乐。

浅谈设计模式之七——Composite模式

标签:设计模式   组合   模板   composite   

原文地址:http://blog.csdn.net/luomoshusheng/article/details/45340407

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!