Factory Method (aka Virtual constructor)

Intent

  • Define an interface for creating an object, but let subclasses decide which class to instantiate.

  • The Factory method lets a class defer instantiation it uses to subclasses.

Problem

  • How can an object be created so that subclasses can redefine which class to instantiate?

  • How can a class defer instantiation to subclasses?

Solution

  • Define a separate operation (factory method) for creating an object.

  • Create an object by calling a factory method.

Advantages

✅ Avoid tight coupling between the creator and the concrete products. ✅ Follows Single Responsibility Principle. As it moves the product creation code into one place in the program, making the code easier to support. ✅ Follows Open/Closed Principle. As it becomes easier to introduce new types of products into the program without breaking existing client code.

Disadvantages

❌ The code may become more complicated since one needs to introduce a lot of new subclasses to implement the pattern.


Note

💡 A similar pattern called Factory also exists, which is similar to factory method. 💡 A factory method is just an addition to Factory class. 💡 It creates the object of the class through interfaces but on the other hand, it also lets the subclass decide which class is instantiated.

Last updated