组合模式

#include <iostream>
#include <string>
#include <list>
using namespace std;


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


//叶子
class Leaf : public Component
{


public:
Leaf(string name):Component(name){}


virtual void Add( Component* c ) 
{
//throw std::exception("The method or operation is not implemented.");
cout << "Can not add to a Leaf....\n";
}


virtual void Remove( Component* c ) 
{
cout << "Can not remove from a Leaf...\n";
}


virtual void Display( int depth ) 
{
string str(depth, '-');
cout << str << name << endl;
}


};


//组合
class Composite : public Component
{
public:
Composite(string name):Component(name)
{
}


virtual void Add( Component* c ) 
{
children.push_back(c);
}


virtual void Remove( Component* c ) 
{
children.remove(c);
}


virtual void Display( int depth ) 
{
string str(depth,'-');
cout << str << name << endl;


for (list<Component*>::iterator i = children.begin(); i != children.end(); ++i)
{
(*i)->Display(depth + 2);
}
}


private:
list<Component*> children;
};




int main(void)
{
Composite *root = new Composite("root");
root->Add(new Leaf("LeafA"));
root->Add(new Leaf("LeafB"));


Composite *comp = new Composite("Composite x");
comp->Add(new Leaf("LeafXA"));
comp->Add(new Leaf("LeafXB"));


root->Add(comp);


comp = new Composite("Composite Y");
comp->Add(new Leaf("LeafYA"));
comp->Add(new Leaf("LeafYB"));


Component *comp1 = new Composite("Composite Z");
comp1->Add(new Leaf("LeafZA"));
comp1->Add(new Leaf("LeafZB"));
comp->Add(comp1);


root->Add(comp);


root->Display(1);


return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值