What is Factory Method Pattern?
Usually, when creating objects in Java most of the time we use the “new” keyword and the object created decided by the constructor. But when it comes to the Factory method pattern object creation is done by factory objects. Developers do not need to know about the implementation of the inside of the class.
Based on the parameters factory classes decide which user to return, Let’s look at an example by using the Factory method pattern using Pizza Shop.
Implementation of Factory Method Pattern
First, we create a base class for the objects we are going to create.
And we create types of Pizzas by extending the base “Pizza ”class.
To create the Pizza first, we have to design an abstract class and call it the Pizza Factory,
Now it has the most common functions which do not depend on the implementation, for example, Baking, Wrapping is must be done to the pizza whichever the shop we are buying. But there might be a unique function depend on each shop. Now Let’s move to the custom implementation where unique functions exist.
Now we override the functions that are unique to a certain factory. Just like this in example price calculation in John’s Pizza Store is different from one another. Now as a client we can use the client object to process the order based on the user’s input and which kind of pizza will get depends on the user’s input.
Complete Source code available here.