Factory Method Pattern in Java

Arjun Sunil Kumar
Software Engineering
2 min readAug 17, 2018

As the name suggests, it is like Factory. Input is a id(raw material), output is a product(finished goods).

Factory Patterns are “Smart Constructors”.

Picture speaks louder than words 😳

Why Factory Method ?

Have you come across a scenario like, same functionality, different structure. For e.g. :-

  • Image (gif, jpeg, png).
  • Printer(dot-matrix, ink-jet, laser)

To handle these scenario’s, we need to instantiate respective objects, dynamically.

Lets dig a little deeper!

I am developing an Image Viewer. In order to render the image, I do the below mentioned.

  • Read the file path. c:\\user\arjunsk\documents\abnormal.png
  • Read the file name and extract the extension format .png(for eg:- .jpeg, .gif, .png)
  • Then create an Image object respective to the format selected. (For eg:- PNGImage, JPEGImage, GIFImage ) (Done via ImageFactory)

Note: Here,
Input is “png”, “jpeg”, “gif”
Output is PNGImageObject, JPEGImageObject etc.

  • Then call the render() for the respective image object created.
  • Similarly we have compress() function etc

Did you feel this like a Strategy pattern 😅?

Note : By using factory method, I could easily support different file formats, that could come in future.

Another Interesting Application:

DVD Player:

These days, DVD players support, DVD, CD, Blue-Ray. All of them are inserted in the same drive. It is the players DiskFactory’s responsibility to instantiate the correct Disk object in run-time. So DiskFactory will instantiate DVDDisk , CDDisk , BlueRayDisk at run-time and output at IDisk object.

Power Socket:

Sometimes, you might connect to Power Socket, some-times you might connect to Laptop port, for charging your phone. The Factory Method Pattern dynamically instantiates USBPower or AdapterPower, based on the power surge.

Project Structure:

Implementation in Java

  1. Create an Interface to hold the basic structure of your Products.

IPrinter.java

2. Create Concrete Product Classes.

InkjetPrinter.java

DotMatrixPrinter.java

LaserPrinter.java

3. Create your Factory Class.

PrinterFactory.java

4. Driver Class to test the Factory.

Found it Interesting?

Please show your support by 👏. To read the complete series, click below.

Reference:

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

--

--

Arjun Sunil Kumar
Software Engineering

Writes on Database Kernel, Distributed Systems, Cloud Technology, Data Engineering & SDE Paradigm. github.com/arjunsk