Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes.
The Factory Method defines a method, which should be used for creating objects instead of using a direct constructor call (new operator). Subclasses can override this method to change the class of objects that will be created.
If you can’t figure out the difference between various factory patterns and concepts, then read our Factory Comparison.
Usage examples: The Factory Method pattern is widely used in Java code. It’s very useful when you need to provide a high level of flexibility for your code.
Identification: Factory methods can be recognized by creation methods that construct objects from concrete classes. While concrete classes are used during the object creation, the return type of the factory methods is usually declared as either an abstract class or an interface.
Production of cross-platform GUI elements
In this example, Buttons play a product role and dialogs act as creators.
Different types of dialogs require their own types of elements. That’s why we create a subclass for each dialog type and override their factory methods.
Now, each dialog type will instantiate proper button classes. Base dialog works with products using their common interface, that’s why its code remains functional after all changes.
buttons
buttons/Button.java: Common product interface
buttons/HtmlButton.java: Concrete product
buttons/WindowsButton.java: One more concrete product
factory
factory/Dialog.java: Base creator
factory/HtmlDialog.java: Concrete creator
factory/WindowsDialog.java: One more concrete creator