组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。
代码:
#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();
}
结果: