设计模式——组合模式

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

        

 代码:

#pragma once
#include <string>
class Component {
public:
	virtual void Add(Component* pCom) = 0;
	virtual void Remove(Component* pCom) = 0;
	virtual void Display(int depth) = 0;
};


#pragma once
#include <iostream>
#include <string>
#include "Component.h"
class Leaf : public Component {
public:
	Leaf(std::string name) : m_leafName(name) {}

	void Add(Component* pCom) {
		std::cout << "叶子节点不允许添加节点" << std::endl;
	}

	void Remove(Component* pCom) {
		std::cout << "叶子节点不允许删除节点" << std::endl;
	}

	void Display(int depth) {
		std::cout << std::string("-", depth) + m_leafName << std::endl;
	}

private:
	std::string m_leafName;
};


#pragma once
#include <iostream>
#include <string>
#include <list>
#include "Component.h"
class Composite : public Component {
public:
	Composite(std::string name) : m_compositeName(name) {
		m_lstComposite.clear();
	}

	void Add(Component *pCom) {
		m_lstComposite.emplace_back(pCom);
	}

	void Remove(Component * pCom) {
		m_lstComposite.remove(pCom);
	}

	void Display(int depth) {
		std::cout << std::string("-", depth) + m_compositeName << std::endl;
		for (auto item : m_lstComposite) {
			item->Display(depth + 1);
		}
	}

private:
	std::string m_compositeName;
	std::list<Component*> m_lstComposite;
};


#include "Composite.h"
#include "Leaf.h"
void main() {
	Composite *root = new Composite("root");
	root->Add(new Leaf("Leaf A"));
	root->Add(new Leaf("Leaf B"));

	Composite *comp = new Composite("Composite X");
	comp->Add(new Leaf("Leaf XA"));
	comp->Add(new Leaf("Leaf XB"));

	root->Add(comp);

	Composite* comp2 = new Composite("Composite XY");
	comp2->Add(new Leaf("Leaf XYA"));
	comp2->Add(new Leaf("Leaf XYB"));

	comp->Add(comp2);

	root->Add(new Leaf("Leaf C"));

	Leaf* leaf = new Leaf("Leaf D");
	root->Add(leaf);
	root->Remove(leaf);

	root->Display(0);
}

客户可以透明一致的使用实体类型,省去不必要的逻辑判断。常见使用场景如:web定制控件、OA系统等。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值