设计模式总篇-组合模式

#define __CRT_SECURE_NO_WARNINGS

/*
@作者:莫忘输赢
@时间:
2020/02/22 12:39
@版本:v1

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

*/


#include<iostream>
#include<vector>
#include<string>
//#include<vld.h>

//节点
class CNode
{
protected:
	std::string m_strName;
public:
	CNode(std::string strName)
	{
		m_strName = strName;
	}
	//添加
	virtual void Add(CNode* c) = 0;
	//展示
	virtual void Display(int nDepth) = 0;
	//职责
	virtual void LineOfDuty( ) = 0;
};
class CanAddNode : public CNode
{
private:
	std::vector<CNode*> m_comList;
public:
	CanAddNode(std::string strName) :CNode(strName){ }
	virtual void Add(CNode* c)
	{
		m_comList.push_back(c);
	}
	virtual void Display(int nDepth)
	{
		std::string strtemp;
		for (int i = 0; i < nDepth; i++)
		{
			strtemp += "-";
		}
		//打印表头
		strtemp += m_strName;
		std::cout << strtemp << std::endl;
		//
		std::vector<CNode*>::iterator  p = m_comList.begin();
		while (p != m_comList.end())
		{
			(*p)->Display(nDepth + 2);
			p++;
		}
	}
	virtual void LineOfDuty()
	{
		std::vector<CNode*>::iterator p = m_comList.begin();
		while (p != m_comList.end())
		{
			(*p)->LineOfDuty();
			p++;
		}
	}
};
class NotCanAddNode : public CNode
{
private:

public:
	NotCanAddNode(std::string strName) :CNode(strName)
	{
	}
	virtual void Add(CNode *c)
	{
		std::cout << "error" << std::endl;
	}
	virtual void Display(int nDepth)
	{
		std::string strtemp;
		for (int i = 0; i < nDepth; i++)
		{
			strtemp += "-";
		}
		strtemp += m_strName;
		std::cout << strtemp << std::endl;
	}
	virtual void LineOfDuty()
	{
		std::cout << m_strName << "的职责" << std::endl;
	}
};
int main(int argc, char **argv)
{
	CanAddNode *p = new CanAddNode("清华大学");

	CanAddNode *p1 = new CanAddNode("数学系");
	NotCanAddNode *p11 = new NotCanAddNode("数学系人才部");
	p1->Add(p11);

	CanAddNode *p2 = new CanAddNode("物理系");
	NotCanAddNode *p21 = new NotCanAddNode("物理系人才部");
	p2->Add(p21);

	p->Add(p1);
	p->Add(p2);

	p->Display(0);
	p->LineOfDuty();

	delete p2;
	delete p21;
	delete p11;
	delete p1;
	delete p;

	return 0;
}
发布了141 篇原创文章 · 获赞 1 · 访问量 5315

猜你喜欢

转载自blog.csdn.net/wjl18270365476/article/details/104451554