目录
C++设计模式-组合(Composite)
一、意图
二、适用性
三、结构
四、参与者
五、代码
C++设计模式-组合(Composite)
一、意图
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
二、适用性
- 你想表示对象的部分-整体层次结构。
-  你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。 
三、结构
 
四、参与者
- Component
为组合中的对象声明接口。
在适当的情况下,实现所有类共有接口的缺省行为。
声明一个接口用于访问和管理Component的子组件。
(可选)在递归结构中定义一个接口,用于访问一个父部件,并在合适的情况下实现它。
- Leaf
在组合中表示叶节点对象,叶节点没有子节点。
在组合中定义图元对象的行为。
- Composite
定义有子部件的那些部件的行为。
存储子部件。
在Component接口中实现与子部件有关的操作。
- Client
通过Component接口操纵组合部件的对象。
五、代码
#include<iostream>
#include<list>
using namespace std;
class Component {
public:
	virtual void Operation() {}
	virtual void Add(Component* tempComponent) {}
	virtual void Remove(Component* tempComponent) {}
	virtual Component* GetChild(int i) { return 0; }
};
class Composite : public Component {
public:
	void Operation() {
		for (auto i : componentList) {
			i->Operation();
		}
	}
	void Add(Component* tempComponent) {
		componentList.push_back(tempComponent);
	}
	void Remove(Component* tempComponent) {
		componentList.remove(tempComponent);
	}
	Component* GetChild(int i) {
		list<Component*>::iterator it = componentList.begin();
		advance(it, i);
		return *it;
	}
private:
	list<Component*> componentList;
};
class Leaf : public Component {
public:
	Leaf(string tempName):name(tempName) {}
	void Operation() {
		cout << "Name : " << this->name << endl;
	}
private:
	string name;
};
int main() {
	Component* p = new Composite();
	p->Add(new Leaf("111"));
	p->Add(new Leaf("222"));
	p->GetChild(1)->Operation();
	p->Operation();
	return 0;
}







![[论文精读]U-Net: Convolutional Networks for BiomedicalImage Segmentation](https://img-blog.csdnimg.cn/30a1f8721cde4330908f8eceacd2e6ff.png)
![[笔记] Windows内核课程:保护模式《二》段寄存器介绍](https://img-blog.csdnimg.cn/e03204ef92904648a8e871910b244787.png)








