Factory Method Pattern in Java

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 😳

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.

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.

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.

  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.

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

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 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store