设计模式——组合模式(C++实现)

本文深入探讨了组合模式,一种用于表示部分-整体层次结构的设计模式,通过C++代码示例展示了如何将对象组合成树形结构,使用户可以一致地操作单个对象和组合对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

组合模式

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

适用场景

      1、你想表示对象的部分 -整体层次结构。
      2、你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
 

采用菜鸟教程的例子,这里用C++实现

#include<iostream>
#include<string>
#include<list>

using namespace std;

//创建Employee类,该类带有Employee对象的列表。
class employee
{
public:
	employee(string tname, string tdept, int tsalary) { name = tname; dept = tdept; salary = tsalary; };
	~employee() {};

	void add(employee e) { subordinates.push_back(e); };
	void remove(employee e) { subordinates.remove(e); };

	string get_name() { return name; };
	string get_dept() {return dept;};
	int get_salary() { return salary; };
	list<employee> get_subordinates() { return subordinates; };
	void toString() { cout << "name: " << name << endl << "dept: " << dept << endl << "salary: " << salary << endl; };

	friend bool operator==(const employee &a, const employee &b);

private:
	string name;
	string dept;
	int salary;

	list<employee> subordinates;
};

bool operator==(const employee &a, const employee &b)
{
	if (a.name == b.name && a.dept == b.dept)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	employee t1("Jhon", "CEO", 30000);
	employee t2("Robert", "Sales", 10000);
	employee t3("Michel", "Support", 10000);
	employee t4("Luara", "Market", 10000);
	employee t5("Bob", "Technique", 15000);

	t1.add(t2);
	t1.add(t3);
	t1.add(t4);
	t1.add(t5);

	t1.toString();
	cout << endl;
	list<employee> iy = t1.get_subordinates();
	list<employee>::iterator it;
	for (it = iy.begin(); it != iy.end(); ++it)
	{
		(*it).toString();
		cout << endl;
	}
	return 0;
}

在visual studio 2015上运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值