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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?