Factory Method#
tl;dr - The Factory Method pattern suggests that you replace direct object construction calls with calls to a special factory method.
The Factory Method 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. The Factory Method pattern suggests that you replace direct object construction calls (using the new operator) with calls to a special factory method.
Components#
Product: This is the common interface for the concrete products the factory method creates.
Concrete Products: These are the different types of products the factory method can create.
Creator: This is the common interface for the concrete creators.
Concrete Creators: These classes override the factory method to change the resulting product’s type.
Nowadays, the Factory method pattern is also often used by classes themselves, when they need to create objects of some specific type, but don’t know the exact subtype beforehand. The factory method will handle the object creation, while subclasses will be able to specify the type of object that will be created. Or if they have an opinionated way of how they themselves should be created, they can provide a factory method to return an instance of themselves. in Java this is often the case with the getInstance() method.
--- UML Diagram ------ Factory Method in Java ---
--- Factory Method in Python ---