Introduction to Factory Method Pattern

Factory method design belongs to Creational design patterns. This pattern is also known as Factory Pattern or Factory Method Pattern.

Unlike Singleton, this pattern is entirely focused on the creation of objects.

We define an interface or abstract class for creating an object in factory method design, and we allow the subclasses to determine which class to instantiate. As a result, with this approach, subclasses are in charge of creating class instances.

The factory method pattern encapsulates the object creation by letting subclasses to decide what objects to create.

When you think of the term “factory method,” you’re thinking of a factory of methods. Objects are created by the factory in this design pattern.

In Singleton, we don’t need any parameters to construct instances, as you may recall. However, a parameter is often used in the Factory method pattern to specify which instance to receive. You can also use default without any parameters, which is perfectly ok.

Let’s see how the implementation of the Factory method design is done. You have to follow the below steps.

1. Inside an abstract define the factory method.

2. Create subclasses that extend above the abstract class. (These subclasses decide the object creation).

Now consider a scenario involving the Factory design pattern. We will implement an application named “global currency” to return exchange rate value for Sri Lanka Rupee. According to the scenario, this application should return a list of international currency rates based on the given inputs.

There is the Currency abstract class. Several money types are implemented using this Currency class (EX: Japanese Yen, US Doller, Australian Doller). There is an ISA relationship between currency and currency kinds in this case. (The Japanese Yen is a currency.) And then I have implemented currency lists so the outcome depends on what kind of currency list you want.

The Source code of the above scenario is available with the below link (Design patterns/ Factory method pattern folder). Hope you will find it helpful.


Associate Software Engineer at Virtusa