How do I implement the builder pattern in web servers with C++?

The Builder Pattern is a creational design pattern that allows you to create complex objects step by step. This pattern is particularly useful in web servers where you may need to construct complex HTTP response objects with various optional settings.

Builder Pattern, C++ Design Patterns, Web Server Development, HTTP Response Builder

This example demonstrates how to implement the Builder Pattern in C++ to construct an HTTP response for a web server.

// HTTPResponseBuilder.h class HTTPResponseBuilder { private: std::string version; int statusCode; std::string statusMessage; std::string body; std::map<:string std::string> headers; public: HTTPResponseBuilder& setVersion(const std::string& ver) { version = ver; return *this; } HTTPResponseBuilder& setStatus(int code, const std::string& message) { statusCode = code; statusMessage = message; return *this; } HTTPResponseBuilder& setBody(const std::string& responseBody) { body = responseBody; return *this; } HTTPResponseBuilder& addHeader(const std::string& key, const std::string& value) { headers[key] = value; return *this; } std::string build() { std::ostringstream response; response << version << " " << statusCode << " " << statusMessage << "\r\n"; for (const auto& header : headers) { response << header.first << ": " << header.second << "\r\n"; } response << "\r\n" << body; return response.str(); } }; // Usage int main() { HTTPResponseBuilder builder; std::string response = builder .setVersion("HTTP/1.1") .setStatus(200, "OK") .setBody("

Hello, World!

") .addHeader("Content-Type", "text/html") .build(); std::cout << response << std::endl; return 0; }

Builder Pattern C++ Design Patterns Web Server Development HTTP Response Builder