c++设计模式(组合模式)

组合模式

  • 将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
  • 需求中是体现部分与整体层次的结构时,希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,考虑使用组合模式
  • 整体和部分可以被一致对待
#include <iostream>
#include <string>
#include <list>
#include <memory>
using namespace std;

//接口
class Componet;
typedef shared_ptr<Componet> COMPONET;
class Componet
{
public:
	Componet(string &_name):name(_name) {}
	virtual ~Componet() = 0 {}
	virtual void Add(COMPONET c) = 0;
	virtual void Remove(COMPONET c) = 0;
	virtual void Display(int depth)
	{
		for (int i = 0; i < depth; i++)
			cout << "-";
		cout << name << endl;
	}
protected:
	string name;
};

//叶子
class Leaf : public Componet
{
public:
	Leaf(string &_name): Componet(_name) {}
	~Leaf() {}

	// 通过 Componet 继承
	virtual void Remove(COMPONET c) override
	{
		cout << "Cannot remove from a leaf" << endl;
	}
	virtual void Display(int depth) override
	{
		Componet::Display(depth);
	}
	virtual void Add(COMPONET c)
	{
		cout << "Cannot add to a leaf" << endl;
	}
};
//分支
class Composite : public Componet
{
public:
	Composite(string &_name) : Componet(_name) {}
	~Composite() {}

	// 通过 Componet 继承
	virtual void Remove(COMPONET c) override
	{
		children.remove(c);
	}
	virtual void Display(int depth) override
	{
		Componet::Display(depth);
		for (auto itr : children)
		{
			itr->Display(depth + 3);
		}
	}
	virtual void Add(COMPONET c)
	{
		children.push_back(c);
	}
private:
	list<COMPONET> children;
};
int main()
{
	//建立根
	COMPONET root(new Composite(string("root")));

	//添加两片叶子到根
	root->Add(COMPONET(new Leaf(string("Leaf A"))));
	root->Add(COMPONET(new Leaf(string("Leaf B"))));

	//创建分支
	COMPONET compositeX(new Composite(string("composite X")));
	compositeX->Add(COMPONET(new Leaf(string("Leaf XA"))));
	compositeX->Add(COMPONET(new Leaf(string("Leaf XB"))));
	//分支挂在根上
	root->Add(compositeX);

	//创建分支
	COMPONET compositeY(new Composite(string("composite Y")));
	compositeY->Add(COMPONET(new Leaf(string("Leaf YA"))));
	compositeY->Add(COMPONET(new Leaf(string("Leaf YB"))));
	//分支挂在另一个分支上
	compositeX->Add(compositeY);

	//添加一片叶子
	root->Add(COMPONET(new Leaf(string("Leaf C"))));

	COMPONET leaf(new Leaf(string("Leaf D")));
	root->Add(leaf);//添加叶子
	root->Remove(leaf);//移除叶子

	//显示树形结构
	root->Display(1);

	getchar();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值