Using the Simple Factory design pattern is a lot like making cheesecake
Software developer Sihui Huang, writing for the blog freeCodeCamp, explains the simple factory design pattern in terms that most people can appreciate – cheesecake.
Huang walks us through the basic steps in a simple factory for creating cheesecake. Starting with a number of his favorite types, he creates a makeCheeseCake() method which calls cheesecake.makeCrust, cheesecake.AddLayers, etc. The makeCheeseCake() method uses the type of cheesecake as a parameter, and calls the the steps to creating a cheesecake that all different types have in common. No matter what kind of cheesecake you are making, you still need to make the crust. So the makeCheeseCake() method is only concerned about the steps required in making any kind of cheesecake, it doesn’t care about what flavor the particular instance is. Huang describes this concept, as we have in class, as encapsulating what varies.
So Huang goes on to create a cheesecake factory class that handles all the different classes of cheesecake we can possibly create, and returns the appropriate cheesecake type by a createCheeseCake() method inside the factory class. The trick is that when you call the makeCheeseCake(), a new cheeseCakeFactory object is created, and uses the createCheeseCake method to determine what type the cheesecake is. So now the MakeCheeseCake() method does not need to know at all about what kind of cheesecake it is creating.
By separating the parts of a program that stay the same from those that vary, we can simplify adding and modifying different types of an object (in this case cheesecake) by adding a new class and adding to the cheeseCakeFactory class. No code has to be rewritten to accommodate for changes and removals of types of cheesecake.
Personally I enjoy Huang’s analogy to elaborate on the simple factory design pattern. Being able to separate varying parts of a program from parts that never change makes our code more understandable, coherent, and easy to modify. And the idea that a “factory” can handle the details of initializing different types of objects instead of having separate implementations for every object type is good design, and I think the cheesecake factory example is a good metaphor for encapsulation
From the blog CS@Worcester – Bit by Bit by rdentremont58 and used with permission of the author. All other rights reserved by the author.