Java Creational Design Patterns – Factory Method Pattern

In this article, we will discuss Factory Method Pattern. This pattern is organized under creational pattern as it deals with the creation of the object.

This design pattern is based on one of the OOPs concept ie. Encapsulation. Generally, we write object creation code on client side program but in factory pattern, we encapsulate object creation code inside factory method. So depending on the data provided to the factory, it can return an object of one of several possible classes listed in a program. You can consider using this pattern when:

  • Your subclasses need to instantiate objects of some classes based on criteria.
  • An application needs to have loose coupling between different classes.

<Here are ALL Java Design Patterns, explained in detail with examples>

Factory Method Pattern by Example

This pattern can be understood with a simple example as below:

We will define an interface that will be implemented by our different concrete classes. Here we have a Country interface which has 2 methods to be implemented.

Note: Here we have tried to use the latest Java 8 feature of default methods. You can read about them in here.

Now let us define a couple of concrete classes which implements an interface.

and another –

The job of the factory method is only created and return objects based on criteria. So it would be best if we keep the method as static.

Running the Example

Output:

In the demo, you can see that the objects are created in the factory method and returned to the client or user for further usage.

Advantages

  • In a complex process, where object creation involves various approaches, this pattern provides a way to centralize the object creation mechanism
  • Code duplication can be avoided
  • Loose coupling is introduced.

Conclusion

In this article, we understood Factory Method Pattern with the help of a simple example. The source code is available in our Github repository.

Download Code

<Here are ALL Java Design Patterns, explained in detail with examples>

Add a Comment

Your email address will not be published. Required fields are marked *