设计模式——组合模式_Composite Pattern

本文深入探讨了组合模式的概念及其在软件设计中的应用,通过UML类图和C++代码实现展示了如何利用组合模式构建树形结构来表示部分-整体的层次关系,以及其在保持代码一致性方面的优势。

组合模式,又称合成模式,部分-整体模式(part-whole)

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.(将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。)


UML类图


C++代码实现

#include <iostream>
#include <vector>
using namespace std;

class Component {
public:
	virtual void Operation()=0;// { cout << "call Component::Operation()" << endl; }
};

class Composite : public Component {
public:
	void Operation() { 
		cout << "call Composite::Operation()" << endl; 
		typedef vector<Component*>::iterator VectIter;
		for (VectIter iter=_VectCom.begin(); iter!=_VectCom.end(); ++iter) {
			(*iter)->Operation();
		}
	}
	void AddItem(Component* comp) { _VectCom.push_back(comp); }
	void RemoveItem(Component* comp) { /*未实现*/ }
	Component* GetChild(int index) { return _VectCom[index]; }

private:
	vector<Component*> _VectCom;
};

class Leaf : public Component {
public:
	void Operation() { cout << "call Leaf::Operation()" << endl; }
};


#include "Composite.h"


int main()
{
	Leaf* I = new Leaf();
	I->Operation();

	Composite* II = new Composite();
	II->AddItem(I);
	II->Operation();

	Component* III = II->GetChild(0);
	III->Operation();

	delete II;
	delete I;
	return 0;
}
组合模式是对DIP原则的破坏。另外,组合模式具有安全模式和透明模式2种。本实现是安全模式

Composite模式通过和Decorator模式有着类似的结构图,但是Composite模式旨在构造类,而 Decorator模式重在不生成子类即可给对象添加职责。Decorator模式重在修饰,而Composite模式重在表示。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值