菜鸟教程 java类图_建造者模式

C++ 方式:

#include

#include

#include

using namespace std;

class Packing {

public:

virtual string pack() {

return "";

};

};

class Item {

public:

virtual string name() {

return "";

};

virtual Packing *packing() {

return new Packing();

};

virtual float price() {

return 0;

};

};

class Wrapper: public Packing {

public:

string pack() {

return "Wrapper";

}

};

class Bottle: public Packing {

public:

string pack() {

return "Bottle";

}

};

class Burger: public Item {

public:

Packing *packing() {

return new Wrapper();

}

};

class ColdDrink: public Item {

public:

Packing *packing() {

return new Bottle();

}

};

class VegBurger: public Burger {

public:

float price() {

return 25.0f;

}

string name() {

return "Veg Burger";

}

};

class ChickenBurger: public Burger {

public:

float price() {

return 50.5f;

}

string name() {

return "Chicken Burger";

}

};

class Coke: public ColdDrink {

public:

float price() {

return 30.0f;

}

string name() {

return "Coke";

}

};

class Pepsi: public ColdDrink {

public:

float price() {

return 35.0f;

}

string name() {

return "Pepsi";

}

};

class Meal {

private:

vector items;

public:

void addItem(Item *item) {

items.push_back(item);

}

float getCost() {

float cost = 0.0f;

for (Item *item : items) {

cost += item -> price();

}

return cost;

}

void showItems() {

for (Item *item : items) {

cout << "Item : " << item -> name() << ", Packing : "

<< item -> packing() -> pack() << ", Price : ";

printf("%.1f\n", item -> price());

}

}

};

class MealBuilder {

public:

Meal *prepareVegMeal() {

Meal *meal = new Meal();

meal -> addItem(new VegBurger());

meal -> addItem(new Coke());

return meal;

}

Meal *prepareNonVegMeal () {

Meal *meal = new Meal();

meal -> addItem(new ChickenBurger());

meal -> addItem(new Pepsi());

return meal;

}

};

int main() {

MealBuilder mealBuilder;

Meal *vegMeal = mealBuilder.prepareVegMeal();

cout << "Veg Meal" << endl;

vegMeal -> showItems();

cout << "Total Cost: " << vegMeal -> getCost() << endl;

delete(vegMeal);

Meal *nonVegMeal = mealBuilder.prepareNonVegMeal();

cout << "\n\nNon-Veg Meal" << endl;

nonVegMeal -> showItems();

cout << "Total Cost: " << nonVegMeal -> getCost() << endl;

delete(nonVegMeal);

}

squid233

squid233

513***220@qq.com4个月前 (11-12)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值