My today’s article about Java is Factory Method pattern.
What is Factory Method?
Well in one word you can call it the “Virtual Constructor” method. And for the long description it is the way to create object (constructor) but the kind of object to be created is left to subclasses to decide.
When to use Factory Method?
- You want to create an extensible framework. This mean you allow some decisions especially for what kind of object to be created can extend and decide later.
- You want a subclass rather than its superclass to decide what kind of an object to create.
- You know when to create an object, but not what kind of an object.
- You want to parameterize the constructor or the getObject() method so that base on different parameters passed the result objects are different too.
Factory Method Example
Let’s me give example by using the Calculator application built in most Windows, you can select various Calculator from Basic to Scientific to Programmer Calculator.
With the above example: Suppose that ScientificCalculator, BasicCalculator and ProgrammerCalculator are all extended the Calculator (base class).