Java: Factory Method Pattern

Akash Panchal
NestedIf
Published in
2 min readJan 21, 2018

A Creational Design Pattern

Photo by John Schnobrich on Unsplash

Before you start, heads up to here for the simple introduction to the design patterns and the index to all the design patterns deep tutorials.

Defined

  • Factory method is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.
  • It provides a way to delegate the instantiation logic to child classes.

Why, When?

  • Useful when it doesn’t know what exact sub-class will be required during execution.
  • Factory method pattern can be used when there is common/generic implementation in a class but the required sub-class is decided dynamically during runtime.

Enough, Show me something

Following example is all you need to understand this design pattern.

We need to have a super class wheel.

Super class in factory design pattern can be an interface, abstract class or a normal java class. We are using abstract class in our example.

Now, we have two sub-classes CarWheel and BikeWheel as below.

Notice that both the class extends Wheel class.

Now that we have super classes and sub-classes ready, we can write our factory class. Here is the basic implementation.

We are ready with super class and sub-class, we can have a factory class: WheelFactory

Let’s have a test drive: TestWheelFactory class

And that’s it. Really! Go, try this.

Code: Find the code used in this article on github.

If you like this post, please click the clap 👏button below a few times to show your support!

Ten clap, twenty clap, sixty?

--

--