您的位置:首页 > 其它

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

2015-04-28 18:40 281 查看
同样地,先上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。

这就是组合模式,祝读者生活快乐。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: