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”.
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.
- 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)
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:
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
BlueRayDisk at run-time and output at
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
AdapterPower, based on the power surge.
Implementation in Java
- Create an Interface to hold the basic structure of your Products.
2. Create Concrete Product Classes.
3. Create your Factory Class.
4. Driver Class to test the Factory.
Found it Interesting?
Please show your support by 👏. To read the complete series, click below.
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 😄