c++组合模式

组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。

在这里插入图片描述
代码:

#pragma once
#pragma warning(disable : 4996)
#include <iostream>
#include <assert.h>
#include <vector>
using namespace std;
class menuComponent {
public:
	virtual void add(menuComponent* m)
	{
		assert(false);
	}
	virtual void remove(menuComponent* m) { assert(false); }
	virtual menuComponent* getChild(int i) { return NULL; }
	virtual string getName(menuComponent* m) { return "no name"; }
	virtual string getDescription() { return "no description"; }
	virtual double getPrice() { return 0.0; }
	virtual bool isVegetarian() { return false; }
	virtual void print() { assert(false); }
};

class menuItem :public menuComponent {
	string name;
	string description;
	bool vegetarian;
	double price;
public:
	menuItem(string nn, string dd, bool vv, double pp) {
		name = nn;
		description = dd;
		vegetarian = vv;

	}
	string getName() { return name; }
	string getDescription() { return description; }
	double getPrice() { return price; }
	bool isVegetarian() { return vegetarian; }
	void print() {
		cout << "name:" << getName() << endl;
		if (isVegetarian()) cout << "Vegetarian:true";
		else cout << "Vegetarian:false";
	}
};

class menu :public menuComponent
{
	vector<menuComponent*> mu;
	string name;
	string description;
public:
	menu(string nn, string dd)
	{
		name = nn;
		description = dd;
	}
	void add(menuComponent* m) { mu.push_back(m); }
	void remove(menuComponent* m) { mu.pop_back(); }
	menuComponent* getChild(int i) { return mu.at(i); }
	string getName() { return name; }
	string getDescription() { return description; }
	void print() {
		cout << "name:" << getName() << endl;
		cout << "description:" << getDescription() << endl;
		cout << "*****************" << endl;

		vector<menuComponent*>::iterator it = mu.begin();
		for (it; it != mu.end(); it++)
		{
			(*it)->print();
		}
	}
};
int main()
{
	menuComponent* pancakeHouseMenu = new menu("pancake house menu", "breakfase");
	menuComponent* dinerMenu = new menu("diner menu", "lunch");
	menuComponent* cafeMenu = new menu("cafe menu", "diner");
	menuComponent* allmenu = new menu("all menu", "all menus combined");
	allmenu->add(pancakeHouseMenu);
	allmenu->add(dinerMenu);
	allmenu->add(cafeMenu);

	pancakeHouseMenu->add(new menuItem("pancake", "pancake description", false, 20));
	dinerMenu->add(new menuItem("diner", "diner description", false, 10.5));
	cafeMenu->add(new menuItem("cafe", "cafe description", true, 8.35));

	allmenu->print();
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值