C++设计模式-组合(Composite)

目录

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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hank_W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值