您的位置:首页 > 其它

设计模式-组合模式

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



讨论模型:在饭店的菜单中有总菜单,总菜单里包含午餐菜单和咖啡菜单,咖啡菜单又包含甜品菜单,每种菜单中都有属于该菜单项的食物,建立一个组合模式使客户可以使用一致的方式处理菜单和食物。

菜单组合MenuComponent基类:

#ifndef MenuComponent_h
#define MenuComponent_h
#include "string.h"
class MenuComponent{
public:
virtual void add(MenuComponent* m){
}
virtual void remove(MenuComponent* m){
}
virtual MenuComponent* getchild(int i){
return nullptr;
}
virtual std::string getName(){
return "";
}
virtual int getPrice(){
return 0;
}
virtual void print(){
}
};

#endif /* MenuComponent_h */


菜单类(整体部分)

#ifndef Menu_h
#define Menu_h
#include "MenuComponent.h"
#include "string.h"
#include "vector"
class Menu:public MenuComponent{
public:
Menu(std::string name){
this->name = name;
}
void add(MenuComponent* m){
v.push_back(m);
}
void remove(MenuComponent* m){
for (auto i = v.begin(); i!=v.end(); i++) {
if (*i == m) {
v.erase(i);
}
}
}
MenuComponent* getchild(int i){
auto j = v.begin();
j+=i;
return *j;
}
std::string getName(){
return name;
}
void print(){
printf("Menu --- Name:%s\n",name.c_str());
for (auto i = v.begin(); i!=v.end(); i++) {
(*i)->print();//根据*i的类型调用不同的print方法
}
}
private:
std::string name;
std::vector<MenuComponent*> v;
};
#endif /* Menu_h */


食物(部分)

#ifndef MenuItem_h
#define MenuItem_h
#include "MenuComponent.h"
#include "string.h"
class MenuItem :public MenuComponent{
public:
MenuItem(std::string name,int price){
this->name = name;
this->price = price;
}

std::string getName(){
return name;
}
int getPrice(){
return price;
}
void print(){
printf("       Menu Item --- Name:%s,price:%d\n",name.c_str(),price);
}
private:
std::string name;
int price;
};

#endif /* MenuItem_h */


#include <iostream>
#include "MenuComponent.h"
#include "MenuItem.h"
#include "Menu.h"

int main(int argc, const char * argv[]) {
auto dinerMenu = new Menu("diner");
auto cafeMenu = new Menu("cafe");
auto dessertMenu = new Menu("dessert");

auto allMenu = new Menu("all");
allMenu->add(dinerMenu);
allMenu->add(cafeMenu);
cafeMenu->add(dessertMenu);

dinerMenu->add(new MenuItem("Pasta",10));
dinerMenu->add(new MenuItem("hum",7));

cafeMenu->add(new MenuItem("mocha",20));

dessertMenu->add(new MenuItem("apple pie",8));

allMenu->print();
return 0;
}


输出:

Menu — Name:all

Menu — Name:diner

Menu Item — Name:Pasta,price:10

Menu Item — Name:hum,price:7

Menu — Name:cafe

Menu — Name:dessert

Menu Item — Name:apple pie,price:8

Menu Item — Name:mocha,price:20

Program ended with exit code: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式