The Factory Pattern is a creational design pattern used in software development, particularly in web servers, to create objects without having to specify the exact class of the object that will be created. This pattern is especially useful when you want to handle a family of related or dependent objects that need to be created in a flexible way. Here's how you can implement the Factory Pattern in a web server application using C++.
// Abstract Product
class RequestHandler {
public:
virtual void handleRequest() = 0;
};
// Concrete Product - Home Request Handler
class HomeRequestHandler : public RequestHandler {
public:
void handleRequest() override {
std::cout << "Handling home request." << std::endl;
}
};
// Concrete Product - About Request Handler
class AboutRequestHandler : public RequestHandler {
public:
void handleRequest() override {
std::cout << "Handling about request." << std::endl;
}
};
// Creator
class RequestHandlerFactory {
public:
static RequestHandler* createHandler(const std::string& type) {
if (type == "home") {
return new HomeRequestHandler();
} else if (type == "about") {
return new AboutRequestHandler();
} else {
return nullptr;
}
}
};
// Usage
int main() {
RequestHandler* handler = RequestHandlerFactory::createHandler("home");
if (handler) {
handler->handleRequest();
delete handler;
}
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?