Factory Method
Table of Contents
1. Creational Design Patterns: Factory Method
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 recommends that, instead of directly calling new operator, use a special factory method. The object created by the factory method is called product.
How does this enable scalability? For example, both ProductA and ProductB classes implement the interface Product, so that for AFactory and BFactory being subclasses of some Factory class, AFactory can return ProductA upon calling createProduct() while BFactory can return ProductB. Moreover, the rest of the codebase treats all products as abstract Product interface.
1.1. Scenarios
- Factory method decouples code using products from code constructing products. This provides extensibility.
- Factory method is suitable if this is a library or framework that users can extend its internal components.
- Factory method is useful if the system has limited resources, through reusing existing objects instead of constructing new ones. For example, let the factory manage a memory pool such that object construction is just returning some member in the pool (with some initialization jobs), rather than manually managing objects all over the codebase.