设计模式 - 组合模式

设计模式- 组合模式

组合模式

定义:将对象组合成树形结构以表示“部分和整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性.

在这里插入图片描述
优点:高层模块调用简单,组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象还是组合对象。
缺点:在使用组合模式时,其子节点和树枝节点都是实现类,而不是接口,违反了依赖倒置原则,设计起来麻烦。

实现

#include<cstdio>
#include<cmath>
#include<map>
#include<vector>
#include<stack>
#include<iostream>
#include<algorithm>
#include<string>
const int maxn=1e5+10;
const int INF=0x3f3f3f3f;
using namespace std;
class Component{
	public:
		Component(string name) {a_name = name;}
		virtual ~Component(){}
		virtual void Add(Component* c){}
		virtual void Display(int depth){}
	protected:
		string a_name;	
}; 
class Leaf:public Component{
	public:
		Leaf(string name):Component(name){}
		virtual void Add(Component* c){
			cout<<"Cannot add a leaf"<<endl;
		}
		void Display(int depth){
			for(int i=0;i<depth;i++) cout<<"-";
			cout<<" "<<a_name<<endl;
		}
		virtual ~Leaf(){}
};
class Reaf:public Component{
	public:
		Reaf(string name):Component(name){}
		virtual ~Reaf(){}
		void Add(Component* c){
			cout<<"Cannot add a Reaf"<<endl;
		}
		void Display(int depth){
			for(int i=0;i<depth;i++) cout<<"-";
			cout<<" "<<a_name<<endl;
		}
}; 
class Composite : public Component{
	private:
		vector<Component *>children;
		vector<Component *>::iterator iter;
	public:
		Composite(string name): Component(name){}
		virtual ~Composite(){}
		virtual void Add(Component* c){
			children.push_back(c);
		}
		void Display(int depth){
			for(int i=0;i<depth;i++) cout<<"-";
			cout<<" "<<a_name<<endl;
			for(iter=children.begin();iter!=children.end();iter++){
				(*iter)->Display(depth+2);
			}
			
		}
};
int main(){
	Component *root = new Composite("company");
	Component *leaf1 = new Leaf("leaf1");
	Component *leaf2 = new Leaf("leaf2");
	root->Add(leaf1);
	root->Add(leaf2);
	Component *mid = new Composite("midCompany");
	Component *leaf3 = new Leaf("leaf3");
	Component *leaf4 = new Leaf("leaf4");
	mid->Add(leaf3);
	mid->Add(leaf4);
	root->Add(mid);
	Component *mid2 = new Composite("mid2Company");
	Component *leaf5 = new Leaf("leaf5");
	Component *leaf6 = new Leaf("leaf6");
	mid2->Add(leaf5);
	mid2->Add(leaf6);
	root->Add(mid2);
	Component *mid3 = new Composite("mid3Company");
	Component *leaf7 = new Leaf("leaf7");
	Component *leaf8 = new Leaf("leaf8");
	mid3->Add(leaf7);
	mid3->Add(leaf8);
	mid2->Add(mid3);
	root->Display(0);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值