The Factory design pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Here’s an example of how the Factory pattern might be implemented in C++:
class Product {
public:
virtual ~Product() {}
};
class ConcreteProductA : public Product {
public:
// Implementation for ConcreteProductA
};
class ConcreteProductB : public Product {
public:
// Implementation for ConcreteProductB
};
class Factory {
public:
virtual Product* create_product() = 0;
};
class ConcreteFactoryA : public Factory {
public:
Product* create_product() {
return new ConcreteProductA;
}
};
class ConcreteFactoryB : public Factory {
public:
Product* create_product() {
return new ConcreteProductB;
}
};
In this example, the Product
class is an interface that defines the interface of the objects that the factory will create. The ConcreteProductA
and ConcreteProductB
classes are concrete implementations of the Product
class. The Factory
class is an interface that defines a method for creating products. The ConcreteFactoryA
and ConcreteFactoryB
classes are concrete implementations of the Factory
class, each with its own implementation of the create_product
method, which creates instances of ConcreteProductA
and ConcreteProductB
respectively.
This allows the client code to use the factory to create objects, without having to know the specific type of object that will be created. This makes the code more flexible, since new types of objects can be added without having to modify the client code.