关于组合模式,JS的DOM、文件系统的目录系统、mp4的一些demux实现都用到了这个模式。
不过我觉得用的比较好的是cocos2d-x引擎,它里面有很多的CCNode就是组合模式的实际实现.由于CCNode的头文件比较长,就不在这里粘贴了。
关于Cocos2d-x的组合模式原文见这里:
http://zilongshanren.com/blog/2012/11/05/cocos2d-x-design-patterns-7-composite/一棵树一般只包含一个根,若干树干和大量的叶子。同时,树干长在树根上,树叶长在树干上。(PS:这有点废话了,不过读者莫急,耐着性着往下看。)对应于Cocos2d-x里面,就是一个游戏有一个主场景GameScene,它是树根,然后它有若干个树干(GameLayer、HudLayer、InputLayer、BackgroundLayer和LevelLayer等),最后,每一个树干又包含若干个树叶(比如sprite、particles、font、TiledMap nodes、etc)
UML图:代码我不自己写了,见多了但是发现这个模式除了在框架程序里面用之外不太在别的地方使用,所以自己也不去单独实现了,下面的代码原文摘自:http://www.cnblogs.com/tiandsp/archive/2012/06/26/2563575.html源码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Composite
{
public:
Composite():_name(""){}
Composite(string name):_name(name){}
virtual ~Composite(){}
virtual void operation()=0;
virtual void add(Composite*){}
virtual void del(Composite*){}
virtual Composite* find(int index){return NULL;}
protected:
string _name;
};
class Leaf : public Composite
{
public:
Leaf(){}
Leaf(string name){_name=name;}
virtual ~Leaf(){}
void operation(){cout<<_name<<endl;}
};
class subComposite : public Composite
{
public:
subComposite():level(0){}
subComposite(string name):level(0){_name=name;}
virtual ~subComposite(){}
void add(Composite*);
void del(Composite*);
Composite* find(int index);
void operation();
private:
vector<Composite*> v_pcom;
int level;
};
void subComposite::add(Composite* com)
{
level++;
v_pcom.push_back(com);
}
void subComposite::del(Composite* com)
{
v_pcom.pop_back();
}
Composite* subComposite::find(int index)
{
return v_pcom[index];
}
void subComposite::operation()
{
for(int i=0;i<level;i++)
cout<<"+";
cout<<_name<<endl;
vector<Composite*>::iterator it;
for (it=v_pcom.begin();it!=v_pcom.end();it++)
{
(*it)->operation();
}
}
int main()
{
Composite* psubcom = new subComposite("动物");
Composite* psubcom1 = new subComposite("非哺乳动物");
Composite* pleaf1 = new Leaf("鸟");
Composite* pleaf2 = new Leaf("鱼");
Composite* psubcom2 = new subComposite("哺乳动物");
Composite* pleaf3 = new Leaf("人");
psubcom1->add(pleaf1);
psubcom1->add(pleaf2);
psubcom2->add(pleaf3);
psubcom->add(psubcom1);
psubcom->add(psubcom2);
psubcom->operation();
delete pleaf1;
delete pleaf2;
delete pleaf3;
delete psubcom1;
delete psubcom2;
delete psubcom;
system("pause");
return 0;
}