The Factory Method pattern is a good place to start, especially if you wish to understand the concept of other factory patterns. It is probably the simplest one and you can implement it for sure.
Imagine a situation that you are the boss of a factory producing something — anything you really want. You are lucky to have a qualified engineer in your team who can create any type of product at your factory provided the specification: TYPE_A or TYPE_B. This is what the Factory Method design pattern is about.
This pattern defines an interface for creating an object but leaves it to the subclasses to decide which class to instantiate. So basically, the Factory Method allows the class to delegate instantiation to subclasses. The goal of any factory is to protect customers from the details of creating copies of classes or class hierarchy. Factory Method is a special case of the Template Method pattern, the variable step of which is responsible for creating the desired type of object.
The Factory Method pattern has the following components:
- Concrete Creator;
- Concrete Product.
These 4 components carry out different functions:
- Creator declares an abstract or virtual method of creating a product. It uses the factory method in its implementation. Samples: Hero Factory, Music Factory, Furniture Factory, DB Factory.
- ConcreteCreator implements a factory method that returns ConcreteProduct. Samples: Rock Music Factory, Door Furniture Factory, MongoDB Factory.
- Product defines the interface of products created by the factory method. Samples: Robot, Detail, Transport, Hero, File, Furniture.
- ConcreteProduct determines the specific type of products. Samples: RobotCleaner, ElfHero, MP3File, Detail13.
Let's make our abstract example from the beginning a little more vivid and detailed. As you remember, you are the boss of a factory. Suppose the factory makes tables: they are truly indispensable in the house. You work with a qualified employee, an engineer, who, as you might have guessed, is your factory method.
First, let's define the abstract class Table:
Second, we should define two specific tables: TableOffice and TableKitchen classes. Note that the abstract class has a constructor, which is sometimes tricky for Java developers with little experience.
Third, let's create your factory. I called it TableStore, the implementation of abstract TableFactory:
Finally, our TestDrive code and the output:
Factory Method comes in handy in situations when you need to:
- have a complicated process for constructing the objects;
- reduce the time to add another product;
- replace one product with another.