Factory Method Design Pattern
Learn about the factory method design pattern.
Why do we need it?
Suppose we have an interface named Car (the interface is implemented using abstract classes in C++), and we have three classes, Ecar
, Dieselcar
, and Sportscar
, that implement the Car interface. Suppose there are different scenarios in which we would create different objects (in this case, different cars). Handling this situation is easy as we can make an algorithm that will decide which car we need to make.
But for the sake of this example, let’s assume that the government decides that a car company can only make 1,000 sports cars per year. After making 1,000 sports cars, the algorithms for creating cars need to change. Therefore, we’d need to change the algorithms for object creation.
We can have other scenarios where we need to change the algorithms for object creation. Essentially, it means that hard coding can’t be an option. As we can see, object creation isn’t simple in this situation. So, how would we create objects in this scenario? ...