模式十一:组合模式(Composite Pattern)——整体与部分一致化

组合模式
允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。
应用分析
组合模式让我们能用树形方式创建对象的结构,树里面包含了组合以及个别的对象。
使用组合结构,我们能把相同的操作应用在组合和个别对象上。话句话说,在大多数情况下,我们可以忽略对象组合和个人别对象之间的差别。

代码分析

//Component.h
#ifndef COMPONENT_H
#define COMPONENT_H

#include <iostream>
#include <string>
#include <list>
#include <algorithm>

class Component//组合和个别的抽象接口
{
public:
	virtual void display()=0;//处理函数
	virtual void add(Component *comTem){};
	virtual void remove(Component *comTem){};
};


class Composite:public Component//组合对象
{
private:
	std::list<Component *> comList;
public:
	void add(Component *comTem)
	{
		comList.push_back(comTem);
	}
	void remove(Component *comTem)
	{
		comList.remove(comTem);
	}
	void display()
	{
		std::list<Component *>::iterator start=comList.begin();
		for(;start!=comList.end();++start)
			(*start)->display();
	}
};

class Leaf:public Component//个别对象
{
private:
	std::string str;
public:
	Leaf(std::string s):str(s){}
	void display()
	{
		std::cout<<str<<std::endl;
	}
};

#endif


//Main.cpp
//测试代码

#include "Component.h"

int main()
{
	Component *L1=new Leaf("1");
	Component *L2=new Leaf("2");
	Component *L3=new Leaf("3");
	Component *L4=new Leaf("4");
	Component *L5=new Leaf("5");

	Component *C1=new Composite();
	C1->add(L1);
	C1->add(L2);

	Component *C2=new Composite();
	C2->add(L3);
	C2->add(L4);

	Component *root=new Composite();
	root->add(C1);
	root->add(C2);
	root->add(L5);

	root->display();

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值