Factory Method Design Pattern

Source: https://refactoring.guru/

🏭 What is factory method 🏭

  • When the class doesn’t know what sub classes should be created
  • When the parent class wants that its sub classes specify the objects should be created
  • When the parent classes choose the creation of objects to its sub-classes

💡 Application of Factory Method

Pros 😃

Cons 😟

Use Case of Factory Method

class diagram for the cakefactory

Implementation 💻

  • Create an abstract class Cake.java to store the common variables and methods of cakes.
  • Create seperated classes for store the different types of cake implementation. ButterCake.java , ChocolateCake.java , BirthDayCake.java , WeddingCake.java and CupCake.java and they should extends the Cake.java class .
  • Now you need a class to store the branch information. So create another abstract class CakeStore.java to store the common branch information.
  • Then create seperate classes [ ABCBakery.java , PQRBakery.java , XYZBakery.java] to store the each branch information and it should extends the CakeStore.java class.
  • To simplify the implementation we create a enum to store the branch information.
  • Above steps are general implementation. Now we move to the Factory Method implementation.To manage the Cake Store information, you need a factory for that. So now we create the CakeStoreFactory.java class.
  • Finally we create the main application [ MainApp.java ] to get the branch details.
  • Here are the output values for above factory method implementation
Bakery has {cake=[ Birth Day Cake,  Wedding Cake,  Cup Cake]}Bakery has {cake=[ Butter Cake,  Chocolate Cake,  Cup Cake]}Bakery has {cake=[ Butter Cake,  Birth Day Cake,  Cup Cake]}



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
Thilini Weerasinghe

Thilini Weerasinghe

Currently working as an Associate Software Engineer at Virtusa. Has completed degree in B.Sc (Hons) Computing & Information Systems. After all I am a Human...