Factory Pattern in C++: What It Is and How It Works
factory pattern in C++ is a design pattern that creates objects without exposing the creation logic to the client. It provides a common interface to create different types of objects, letting subclasses decide which class to instantiate.How It Works
The factory pattern works like a factory in real life that produces different products based on demand. Instead of creating objects directly in your code, you ask the factory to make the object for you. This way, the code that uses the objects doesn't need to know the details of how they are created or which exact class is used.
Imagine you want to buy a vehicle but don't want to decide the exact model yourself. You tell the factory your needs, and it gives you the right vehicle. Similarly, in C++, the factory pattern uses a common interface or base class and creates objects of different derived classes based on input or conditions.
Example
This example shows a simple factory that creates different types of shapes (Circle, Square) based on a string input.
#include <iostream> #include <memory> #include <string> // Base class class Shape { public: virtual void draw() const = 0; virtual ~Shape() = default; }; // Derived classes class Circle : public Shape { public: void draw() const override { std::cout << "Drawing a Circle" << std::endl; } }; class Square : public Shape { public: void draw() const override { std::cout << "Drawing a Square" << std::endl; } }; // Factory class class ShapeFactory { public: static std::unique_ptr<Shape> createShape(const std::string& type) { if (type == "circle") { return std::make_unique<Circle>(); } else if (type == "square") { return std::make_unique<Square>(); } else { return nullptr; } } }; int main() { auto shape1 = ShapeFactory::createShape("circle"); if (shape1) shape1->draw(); auto shape2 = ShapeFactory::createShape("square"); if (shape2) shape2->draw(); return 0; }
When to Use
Use the factory pattern when your code needs to create objects from a family of related classes but you want to keep the creation logic separate from the main code. It helps when the exact types of objects might change or grow over time.
For example, in a graphics program, you might want to create different shapes or tools without changing the main program. Or in a game, you might create different enemy types based on the level. The factory pattern makes your code easier to maintain and extend.
Key Points
- The factory pattern hides object creation details from the user.
- It uses a common interface or base class for all created objects.
- It helps manage and organize code when many related classes exist.
- It improves flexibility and maintainability of code.