StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Sunday, March 31, 2013

C++ Builder Design Pattern

 March 31, 2013     Design Patterns     No comments   

Builder design pattern in useful when you want to build a complex object. Intent of this pattern is to separate the construction of object from its representation. In this article, we will explore builder design pattern with a simple implementation in C++.

Builder Design Pattern

  • Builder pattern in useful when you want to build a complex object. Intent of this pattern is to separate the construction of object from its representation.
  • Abstract the construction of object and then derived concrete implementations will give respective construction parts.
  • The director makes sure that the product (complex object) is properly created using the builder interface and the parts are built with correct order.

Builder design pattern implementation

Below example shows an implementation with a multi-cuisine cook cooking different meals. Treat Meal as a complete product, in that sense well known examples of pizza or maze make better products (look more tightly coupled product than the meal used here).

#include <iostream>
#include <string>
#include <queue>

using namespace std;

// Product
class Meal {
public:
    Meal() {}
    ~Meal() {}

    void setMealItem(string mealItem) { mMeal.push(mealItem);}
    void serveMeal() {
        int i = 1;
        while(!mMeal.empty()) {
            cout << " Serve item " << i++ << ":" << mMeal.front() << endl ;
            mMeal.pop();
          }
    }

private:
    queue <string> mMeal;
};

// Builder
class MealBuilder {
public:
    MealBuilder() {}
    ~MealBuilder() {}

    const Meal& getMeal() { return mMeal; }
    virtual void buildStarter() = 0;
    virtual void buildMainCourse() = 0;
    virtual void buildDessert() = 0;

protected:
    Meal mMeal;
};

// Director: Makes sure the right sequence of food is prepared and served.
class MultiCuisineCook {
public:
    MultiCuisineCook():mMealBuilder(NULL) {}
    ~MultiCuisineCook() { if (mMealBuilder) delete mMealBuilder;}

    void setMealBuilder(MealBuilder *mealBuilder) {
        if (mMealBuilder) delete mMealBuilder;
        mMealBuilder = mealBuilder;
    }

    const Meal& getMeal() { return mMealBuilder->getMeal(); }

    void  createMeal() {
        mMealBuilder->buildStarter();
        mMealBuilder->buildMainCourse();
        mMealBuilder->buildDessert();
    }

private:
    MealBuilder *mMealBuilder;

};

// Concrete Meal Builder 1
class IndianMealBuilder : public MealBuilder {
public:
    IndianMealBuilder() {}
    ~IndianMealBuilder() {}

    void buildStarter() { mMeal.setMealItem("FriedOnion");}
    void buildMainCourse() { mMeal.setMealItem("CheeseCurry");}
    void buildDessert() { mMeal.setMealItem("SweetBalls");}

};

// Concrete Meal Builder 2
class ChineeseMealBuilder : public MealBuilder {
public:
    ChineeseMealBuilder() {}
    ~ChineeseMealBuilder() {}

    void buildStarter() { mMeal.setMealItem("Manchurian");}
    void buildMainCourse() { mMeal.setMealItem("FriedNoodles");}
    void buildDessert() { mMeal.setMealItem("MangoPudding");}

};

// Concrete Meal Builder 3
class MexicanMealBuilder : public MealBuilder {
public:
    MexicanMealBuilder() {}
    ~MexicanMealBuilder() {}

    void buildStarter() { mMeal.setMealItem("ChipsNSalsa");}
    void buildMainCourse() { mMeal.setMealItem("RiceTacoBeans");}
    void buildDessert() { mMeal.setMealItem("FriedIcecream");}

};

int main()
{
    MultiCuisineCook cook;

    cout << "Build a Chineese Meal!" << endl;
    cook.setMealBuilder(new ChineeseMealBuilder());
    cook.createMeal();

    Meal chineeseMeal = cook.getMeal();
    chineeseMeal.serveMeal();

    cout << "Build a Mexican Meal!" << endl;
    cook.setMealBuilder(new MexicanMealBuilder());
    cook.createMeal();

    Meal mexicanMeal = cook.getMeal();
    mexicanMeal.serveMeal();

    return 0;
}
Output:-
Build a Chineese Meal! 
 Serve item 1:Manchurian 
 Serve item 2:FriedNoodles 
 Serve item 3:MangoPudding 
Build a Mexican Meal! 
 Serve item 1:ChipsNSalsa 
 Serve item 2:RiceTacoBeans 
 Serve item 3:FriedIcecream
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • C++ Template PatternTemplate design pattern is a behavioral design pattern. In the template pattern, parts of program which are well defined like an algorithm are defined… Read More
  • C++ Chain of Responsibility Design PatternChain of Responsibility is a behavioral design pattern. The basic idea behind this pattern is that a request or a command passes through a chain of ob… Read More
  • C++ Observer Design PatternObserver design pattern is a behavioral design pattern and used to notify multiple objects of a change to keep them in sync like Model-View-Controller… Read More
  • C++ Command Design PatternCommand pattern is a behavioral design pattern where the command or request is encapsulated and treated as a object. This article talks about the vari… Read More
  • C++ Factory Design PatternFactory design pattern is a creation design pattern to localize the object creation code and prevents disturbing the entire system for a new type intr… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © 2025 StackStalk