(十四)Head first design patterns建造者模式(c++)

建造者模式

建造者把产品细节的实现过程单独封装成类,完成产品本身和创建产品之间的解耦。每一个建造者都相对独立,因此在建造细节实现方面实现了灵活性和可扩展性。

建造者模式和工厂模式的区别:工厂模式关心把这个产品创建出来,而不关心其细节;建造者模式不仅需要把产品生产出来,还需要关心生产细节。

建造者的核心在于将建造者独立成不同的子类,以实现建造过程的灵活性和可扩展性。

示例代码

#include<iostream>
#include<string>
using namespace std;


class Meal{
public:
    void setBurger(string str){
        burger = str;
    }
    void setFries(string str){
        fries = str;
    }
    void setDrink(string str){
        drink = str;
    }
    void print(){
        std::cout << burger << std::endl;
        std::cout << fries << std::endl;
        std::cout << drink << std::endl;
    }
private:
    string burger;
    string fries;
    string drink;
};
class MealBuilder{
public:
    virtual void buildBurger(){}
    virtual void buildFries(){}
    virtual void buildDrink(){}
    virtual Meal* getMeal(){
        return meal;
    }

    Meal* meal = new Meal();
};
class ChickenMealBuilder : public MealBuilder{
public:
    void buildBurger(){
        meal->setBurger("鸡肉汉堡");
    }
    void buildFries(){
        meal->setFries("中份薯条");
    }
    void buildDrink(){
        meal->setDrink("大杯果汁");
    }
};
class BeefBurgerMealBuilder : public MealBuilder{
public:
    void buildBurger(){
        meal->setBurger("牛肉汉堡");
    }
    void buildFries(){
        meal->setFries("大份薯条");
    }
    void buildDrink(){
        meal->setDrink("中杯可乐");
    }
};
class ShrimpMealBuilder : public MealBuilder{
public:
    void buildBurger(){
        meal->setBurger("虾肉汉堡");
    }
    void buildFries(){
        meal->setFries("小份薯条");
    }
    void buildDrink(){
        meal->setDrink("大杯芬达");
    }
};
class MealDirector{
public:
    void setMealBuilder(MealBuilder* mealBuilder){
        this->mealBuilder = mealBuilder;
    }
    Meal* getMeal(){ return mealBuilder->getMeal(); }
    void constructMeal(){
        mealBuilder->buildBurger();
        mealBuilder->buildFries();
        mealBuilder->buildDrink();
    }
private:
    MealBuilder* mealBuilder;
};
int main(){
    MealDirector* director = new MealDirector();
    director->setMealBuilder(new BeefBurgerMealBuilder());
    director->constructMeal();
    Meal* meal = director->getMeal();
    meal->print();
}