Factory Method Pattern
- is a creational pattern that uses a SINGLE method to create objects
Factory Method Pattern - Example Implementation
First, create a Polygon interface
interface Polygon {
String getType();
}Next, create a few Polygon implementations like Square, Triangle, etc
|
|
| |
Factory Method Implementations and Uses Cases
|
Factory Method Implementation #1
|
Factory Method Implementation #2
|
|
Use case |
Use case |
Comparisons
Click here to expand...
Link to originalAbstract Factory Pattern vs Factory Method Pattern
- the main difference is that the factory method is a method, and an abstract factory is an object
- the intended purpose of the class containing a factory method is NOT to create objects
- the intended purpose of an abstract factory should ONLY be used to create objects
- abstract factory is implemented by composition, but factory method is implemented by Inheritance
- goals:
- abstract factory’s goal is to create a family of objects that are designed to work together
- factory method’s goal is to encapsulate object creation in a separate method, allowing subclasses to provide the implementation for creating specific objects
- one should take care when using factory methods since it’s easy to break the Liskov Substitution Principle (LSP) when creating objects
Link to originalFactory Method Pattern vs Static Factory Method Pattern
- Static Factory Method Pattern does not allow overriding
- Factory Method Pattern allows overriding for flexibility before compile time
Link to originalFactory Method Pattern vs Template Method Pattern
- Factory Method is a specialization of Template Method used specifically for creating objects rather than containing business logic
- At the same time, a Factory Method may serve as a step in a large Template Method
Other
- Utilizes Strategy Pattern for object creation
- Factory Kit Pattern - used to create/define factory methods during runtime