1.概念
建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。
我们假设一个快餐店的商业案例,其中,一个典型的套餐可以是一个汉堡(Burger)和一杯冷饮(Cold drink)。汉堡(Burger)可以是素食汉堡(Veg Burger)或鸡肉汉堡(Chicken Burger),它们是包在纸盒中。冷饮(Cold drink)可以是可口可乐(coke)或百事可乐(pepsi),它们是装在瓶子中。
我们将创建一个表示食物条目(比如汉堡和冷饮)的 Item 接口和实现 Item 接口的实体类,以及一个表示食物包装的 Packing 接口和实现 Packing 接口的实体类,汉堡是包在纸盒中,冷饮是装在瓶子中。
然后我们创建一个 Meal 类,带有 Item 的 List 和一个通过结合 Item 来创建不同类型的 Meal 对象的 MealBuilder。
2.代码:
#include <iostream>
#include <list>
using namespace std;
class Packing {
public:
virtual string pack()=0;
virtual ~Packing(){};//基类析构函数最好做成虚函数,不然析构时会破环多态性,不会调用子类的析构
};
class Item {
public:
virtual string name()=0;
virtual Packing* packing() = 0;
virtual float price() = 0;
virtual ~Item() {};
};
class Wrapper:public Packing {
public:
virtual string pack()override {
return "wrapper";
}
};
class Bottle :public Packing {
public:
virtual string pack()override {
return "bottle";
}
};
class Burger :public Item {
public:
virtual Packing* packing()override {
return new Wrapper();
}
};
class VerBurger :public Burger {
public:
virtual string name()override {
return "verBurger";
}
virtual float price()override {
return 10.f;
}
};
class ChickenBurger :public Burger {
public:
virtual string name()override {
return "chickenBurger";
}
virtual float price()override {
return 20.f;
}
};
class ColdDrink :public Item {
public:
virtual Packing* packing()override {
return new Bottle();
}
};
class Pepsi :public ColdDrink {
virtual string name()override {
return "pepsi";
}
virtual float price()override {
return 5.f;
}
};
class Coke :public ColdDrink {
virtual string name()override {
return "coke";
}
virtual float price()override {
return 15.f;
}
};
class Meal {
public:
list<Item*> m_items;
void addItem(Item* item) {
m_items.push_back(item);
}
float getCost() {
float _cost=0.0f;
for (auto item : m_items)
{
_cost += item->price();
}
return _cost;
}
void showItems() {
for (auto item : m_items)
{
cout << item->name() << "," << item->packing()->pack() << "," << item->price() << endl;
}
}
~Meal() {
for (auto& item : m_items)
{
delete item;
}
m_items.clear();
}
};
class MealBuilder {
public:
Meal* prepareVegMeal() {
Meal* meal = new Meal();
meal->addItem(new VerBurger());
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 builder;
Meal* nonMeal=builder.prepareNonVegMeal();
nonMeal->showItems();
cout << "cost:" << nonMeal->getCost()<< endl;
cout << "----------------"<<endl;
Meal* vegMeal = builder.prepareVegMeal();
vegMeal->showItems();
cout << "cost:" << vegMeal->getCost() << endl;
cout << "----------------" << endl;
}
3.类图:
4.参考资料: