Java Design Patterns – Factory Method Pattern

The Factory Method is very simple and easy to learn and use. This design pattern is from creational patterns group. The Factory Method helps create objects that have the same type.

In this post, you can find:

  • example situation when to use Factory Method design pattern
  • Factory Method pattern code structure in Java
  • example how to use Factory Method

Exemplary Situation

There is a lot of nationalities and languages in the world. We have Americans, Spanish, Poles etc. All these peoples are humans. I know how stupid it sounds but the point is all peoples have something in common. For example, all humans can say hello. Each one in own language. Based on this example we can write code with Factory Method pattern.
Let’s code it!

Factory Method pattern example in Java

We would have the interface named Human and class like American, Spanish that would implement Human interfaces. In the end, we would create Factory class named HumanFactory (that’s not a science-fiction :)).

Interface Human

Simple interface with method sayHello(). You can add more methods on your own.

Classes that implement the Human interface

I created three classes: American, Spanish, Pole but of course you can add more.

As you can see, we implement method sayHello() and create own response in each one.

Class HumanFactory

Here, we have the method getHuman() that use country code as a parameter and create a proper object.

How to use Factory Method?

Here it the Client class:

Console output:

Factory Method console output

Factory Method design pattern is, as you can see, very easy to use. First, we create the HumanFactory object. Next, we create variable with type Human and we use getHuman() method. Then we initialize sayHello() method on the variable. In the end, the output from Client class you can see in the console.

You can find the code used in this article on my GitHub: Factory Method

How easy it is! Write this code on your own. Modify and test it. Write Factory Method pattern on your own example. That’s the best way to learn it.
Good luck!

Want more? Look at my others post about Design Patterns

Be First to Comment

Leave a Reply

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