Factory Design Pattern – Factory Method

In this week’s blog post I decided to share an informative post by Henri Idrovo on dev.to detailing the implementation and usage of the factory design pattern, specifically the “Factory Method.” Henri starts the blog by introducing the problem the factory design pattern is aiming to solve: using the ‘new’ keyword creates dependencies on concrete classes within our program. When many new objects are being created, this tends to get out of hand. Henri introduced the dependency inversion principle, stating “Depend upon abstractions. Do not depend on concrete classes.”

To show how to implement and improve your code using the factory design pattern, an example is introduced that involves a Pizza Store that has to create different types of pizzas. Without the design pattern in place, every type of pizza you would want to make would require another if-statement, so clearly something needs to be fixed. In order to use the factory pattern, we need to separate what is likely to change from what is not, and put what will change in a class of their own.

In Henri’s example everything that is common to pizza creation is placed in an abstract creator class, and the specifics are placed in concrete creator classes that extend the abstract class. Similarly, the different kinds of Pizza are each given their own concrete product class that extends the abstract Pizza class.

The factory method seemed hard to understand at first, but after going through the examples given in the blog it became clear to me, and the advantages of using the factory method are clear. By relying on abstractions instead of concrete classes, you are removing dependencies within your code and making it much more open for modification. Whereas prior to applying the method, the handling of creation of pizza objects was handled within the PizzaStore class itself, it is now handled within concrete sub-classes that can also handle different categories of pizzas. Also, personally it is easier to read the code of the PizzaStore class after applying the factory method, and it is much more clean in the abstraction. I can see the factory method being useful in any situation where you have to deal with the creation of a lot of categorically related but different objects.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s