组合模式(Composite)

1.目的

   有的需要将对象组织成树形结构,分为枝节点和叶节点,枝节点持有叶节点,同时需要枝节点和叶节点具有相同的行为(对外暴露同样的接口)


2.代码

composite.h

#ifndef COMPOSITE_H_
#define COMPOSITE_H_
#include <list>
#include <string>
#include <iostream>
using namespace std;

class Component
{
public:
	Component(string arg):name(arg)
	{}
	virtual ~Component()
	{}
	virtual void add(Component&)=0;
	virtual void del(Component&)=0;
	virtual void display()=0;
protected:
	string name;
};

class Composite: public Component
{
public:
	Composite(string arg):Component(arg)
	{}
	void add(Component& arg)
	{
		lists.push_back(&arg);
	}

	void del(Component& arg)
	{
		lists.remove(&arg);
	}

	void display()
	{
		cout<<"--"<<name<<endl;
		list<Component*>::iterator iter = lists.begin();
		while(iter != lists.end())
		{
			(*iter)->display();
			iter++;
		}
	}
private:
	list<Component*> lists;
};

class Leaf: public Component
{
public:
	Leaf(string arg):Component(arg)
	{}
	void add(Component& arg)
	{
		cout<<"can not call this "<<endl;
	}

	void del(Component& arg)
	{
		cout<<"can not call this "<<endl;
	}

	void display()
	{
		cout<<"----"<<name<<endl;
	}
};

#endif /* COMPOSITE_H_ */

composite.cpp

#include "Composite.h"

void composite()
{
	Composite root("root");

	Composite level1("level1");
	Leaf leaf11("Leaf11");
	Leaf leaf12("Leaf12");

	Composite level2("level2");
	Leaf leaf21("Leaf21");
	Leaf leaf22("Leaf22");
	Leaf leaf23("Leaf23");

	level2.add(leaf21);
	level2.add(leaf22);
	level2.add(leaf23);

	level1.add(leaf11);
	level1.add(leaf12);

	root.add(level1);
	root.add(level2);

	root.display();
}

执行结果:

--root
--level1
----Leaf11
----Leaf12
--level2
----Leaf21
----Leaf22
----Leaf23

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值