CreationalC++verifiedVerified

Builder Pattern in C++

Separates the construction of a complex object from its representation, allowing the same construction process to produce different results.

How to Implement the Builder Pattern in C++

1Step 1: Define the product

struct HttpRequest {
    std::string method;
    std::string url;
    std::vector<std::pair<std::string, std::string>> headers;
    std::optional<std::string> body;
};

2Step 2: Implement the builder with fluent interface

class RequestBuilder {
    HttpRequest req_;

public:
    RequestBuilder& method(const std::string& m) { req_.method = m; return *this; }
    RequestBuilder& url(const std::string& u) { req_.url = u; return *this; }

    RequestBuilder& header(const std::string& key, const std::string& val) {
        req_.headers.emplace_back(key, val);
        return *this;
    }

    RequestBuilder& body(const std::string& b) { req_.body = b; return *this; }

    HttpRequest build() { return std::move(req_); }
};

3Step 3: Client code uses the builder

int main() {
    auto request = RequestBuilder()
        .method("POST")
        .url("https://api.example.com/data")
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token123")
        .body(R"({"key":"value"})")
        .build();

    std::cout << request.method << " " << request.url << "\n";
    for (const auto& [k, v] : request.headers)
        std::cout << k << ": " << v << "\n";
    if (request.body) std::cout << "Body: " << *request.body << "\n";
}

Builder Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Builder Pattern in the Real World

Consider ordering a custom sandwich at a deli. You tell the sandwich artist (builder) each step — bread type, protein, toppings, sauce — and they assemble it in the right order. You don’t need to know how to layer ingredients properly; you just specify what you want, and the builder hands you a finished sandwich.