组合模式

我们先看一个典型的UNIX文件系统,大家都知道UNIX文件系统采用的是多级索引结构,本图只给出了两级构架,其中直接物理块里存放的是文件的直接地址,而次级索引表指向一个和顶级索引表类的东西,这样就成了一个树形的构架,组合成了一个文件系统。


组合模式,将对象组合成树形结构以表示‘部分-整体’的层次构架。组合模式使得用户对单个对象和组合对象的使用具有一致性。


Component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为,声明一个接口用于访问和管理Component的子部件。

   Leaf在组合中表示叶节点对象,叶节点没有子节点。

   Composite定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如增加Add和删除Remove。

   需要注意的是,Leaf中通常也会实现Add和Remove方法,虽然Leaf是不能在添加子节点的,这是为什么呢?这样做的好处就是在外界看来叶节点和枝节点没有区别,具备完全一致的接口行为,这样使用者就可以不用区分了,这种方式叫透明方式。当然了这种方法也是有问题的,因为对于Leaf来说,这种方法没有任何意义。当然了,还有另外一种做法,就是在Component中不声明Add和Remove方法,只在Composite中声明,这样Leaf就不用关系Add和Remove了。

     使用场景,当你发现需求中是体现部分和整体层次的构架时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就可以考虑使用组合模式了。

#include<iostream>
#include<list>
#include<string>
using namespace std;
class Component
{
protected:
	string name;
public:
	 Component(string _name) :name(_name)
	{}
	virtual void Add(Component *c) = 0;
	virtual void Remove(Component *c) = 0;
	virtual void Display(int depth) = 0;
	virtual ~Component()
	{}
};
class Leaf : public Component
{
public:
	Leaf(string name) :Component(name)
	{}
	void Add(Component *c)
	{
		cout << "Cannot add to a leaf" << endl;
	}
	void Remove(Component *c)
	{
		cout << "Connout remove from a leaf" << endl;
	}
	void Display(int depth)
	{
		string str(depth, '-');
		cout << str << " " << name << endl;
	}
};
class Composite : public Component
{
private:
	list<Component*>l;
public:
	Composite(string name) :Component(name)
	{}
	void Add(Component *c)
	{
		l.push_back(c);
	}
	void Remove(Component *c)
	{
		list<Component*>::iterator p = l.begin();
		while (p != l.end())
		{
			if (*p == c)p = l.erase(p);
			else p++;
		}
	}
	void Display(int depth)
	{
		string str(depth, '-');
		str += name;
		cout << str << endl;
		list<Component*>::iterator p = l.begin();
		for (; p != l.end(); p++)
		{
			(*p)->Display(depth+2);
		}
	}
};
int main()
{
	Component* root = new Composite("root");
	root->Add(new Leaf("Leaf A"));
	root->Add(new Leaf("Leaf B"));
	Component* compx = new Composite("Composite X");
	compx->Add(new Leaf("Leaf XA"));
	compx->Add(new Leaf("Leaf XB"));
	root->Add(compx);
	Component* compxy = new Composite("Composite XY");
	compxy->Add(new Leaf("Leaf XYA"));
	compxy->Add(new Leaf("Leaf XYB"));
	compx->Add(compxy);
	root->Display(1);
	delete root;
	delete compx;
	delete compxy;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值