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)