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

发布时间:2024年01月23日

建造者模式

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

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

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

示例代码

#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();
}

文章来源:https://blog.csdn.net/weixin_44194690/article/details/135765618
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。