-
Notifications
You must be signed in to change notification settings - Fork 0
Factory Method
Roberto Fronteddu edited this page Jan 28, 2023
·
4 revisions
The Factory Method is a Creational Design Pattern. The idea is to move class creation logic out of the client by hiding it behind the concrete implementation of an interface.
- We have to move the object creation logic from our code to a separate class.
- We do not know in advance which class we may need to instantiate beforehand and also we want to allow new classes to be added to the system and handle their creation without affecting the client code.
- We let subclasses decide which object to instantiate by overriding the factory method.
- Create the Creator Class
- The Creator can be concrete if it can provide a default object or it can be abstract. Implementations will override the creation method and return an object.
- Product class: Base class or interface of products created by the factory method
- ProductA and ProductB: Are the product implementations
- Creator: Declare the abstract factory method, additionally, uses the factory method to create a product.
- CreatorA and CreatorB: Implement the factory method and return one of the concrete product instances.
- The creator can be a concrete class and provide a default implementation for the factory method. In such cases, you will create some default objects in the base creator.
- Simple Factory can accept additional arguments to specialize between different object types. Subclasses can then override the factory method to selectively create different objects for some criteria.
- Template Method Design Patter often makes use of Factory Methods.
- Abstract Factory Design Pattern makes use of Factory Method pattern.
- The most defining characteristic of the Factory Method is that subclasses are providing a concrete implementation of that particular class.
- More classes involved and need unit testing
- Not easy to refactor existing code into this pattern
- Sometimes this pattern forces you to subclass just to create the appropriate instance.
- java.util.Collection has an abstract method called iterator(). This method is an example of a Factory Method.