Builder Design Pattern

Builder Design pattern is one of the creational design pattern.

This pattern allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.







Example

#include<iostream>
using namespace std;

class Meal
{
    public:
        string Sandwich;
        string Drink;
        string Sideitem;
        int price;
        void ServeMeal()
        {
            cout<<"Your order please"<<endl;
            cout<<Sandwich<<endl<<Drink<<endl<<Sideitem<<endl<<endl;
            cout<<"Your Bill : "<<price<<endl;
        }
};

class MealBuilder
{
    public:
        virtual void AddDrink() = 0;
        virtual void AddSandwich() = 0;
        virtual void AddSideItem() = 0;
        virtual void GenerateBill() = 0;
        virtual Meal GetMeal() = 0;
};

class VegMeal : public MealBuilder
{
    Meal m;
    public:
        void AddDrink()
        {
            m.Drink = "Orange Juice";
        }
        void AddSandwich()
        {
            m.Sandwich = "Veg Burger";
        }
        void AddSideItem()
        {
            m.Sideitem = "Fries";
        }
        void GenerateBill()
        {
            m.price = 200;
        }
        Meal GetMeal()
        {
            return m;
        }
};

class NonVegMeal : public MealBuilder
{
    Meal m;
    public:
        void AddDrink()
        {
            m.Drink = "Taquila";
        }
        void AddSandwich()
        {
            m.Sandwich = "Spicy Burger";
        }
        void AddSideItem()
        {
            m.Sideitem = "Chicken";
        }
        void GenerateBill()
        {
            m.price = 300;
        }
        Meal GetMeal()
        {
            return m;
        }
};

class MealDirector
{
    public:
        void CreateMeal(MealBuilder *mb)
        {
            mb->AddDrink();
            mb->AddSandwich();
            mb->AddSideItem();
            mb->GenerateBill();
        }
};

int main()
{
    MealBuilder *mb = new VegMeal;
    MealDirector md;
    md.CreateMeal(mb);
    Meal m = mb->GetMeal();
    m.ServeMeal();
    return 0;
}

Output

Your order please
Veg Burger
Orange Juice
Fries

Your Bill : 200

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions