同样地,先上uml图: 组合模式的意图:将对象组合合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。 uml解析:leaf是叶节点,Composite可以理解为是一个多个叶节点的组合,它是非叶节点,就相当于一个元件以及一个元件容器,里面有很多元件一样。这里可以用list或者vector实现。 本来是想用模板来实现,后来发现实在是多此一举,而且反而更不好了。 这里需要说的一点就是Leaf是叶节点,因此肯定没有添加、删除等功能,因为这些是没有意义的,这一点也是组合模式需要考虑的问题吧,这样会使得操作Leaf跟Composite会有少许的不同。 下面给出可执行代码: Composition.h
#pragma once #include #include #include #include using namespace std; /*template*/ 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 m_Com; }; // template 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*/ bool Composite::Remove(Component &leaf) { vector::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::iterator itor = m_Com.begin(); for (;itor!=m_Com.end();itor++) { (*itor)->Display(); } } Leaf::Leaf(std::string &str):mstring(str) { } // template void Leaf::Display() { cout<
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模式