Creational Design Patterns #1: Factory Method

Factory method provides an interface for creating objects in a superclass, allowing the inherited subclasses to alter the type of objects

Vijayasri Iyer
3 min readNov 27, 2023

Imagine that you are the owner of a restaurant that specializes in Indian cuisine. You have two meal options : regular and premium. Each meal consists of rice, roti, dal, a curry and a sweet dish. The food options in both the meal options along with class diagram of the menu is illustrated in detail below.

Regular Meal : Plain Rice, Plain Roti, Dal, Mixed Veg, Halwa

Premium Meal : Biryani, Naan, Dal Fry, Paneer Veg, Gulab Jamun

Fig 1. Class structure of Menu

In the meal options, you can notice that the main items such as rice, roti etc. remain constant and the ingredients are varied across different meals. When you need to simulate such a situation where the type of objects created need to be altered such as plain rice or biryani, the factory pattern proves to be really useful. Let us try to simulate the meal preparation and assembly scenario using the factory method.

There are 3 main classes for this scenario

  1. Item class — This is the parent class for all the individual meal items (The class structure for this class is illustrated in Fig 1.)
  2. Meal class — This is the parent class for the different types of meals. This holds all information about each meal including which items to make. The structure for this class is provided in Fig 2.
  3. MealKitchen class — The class responsible for preparation of meals. This is the factory class in our example.
Fig 2. Class Structure for Meals

Since we have designed our class structure and assigned responsibilities to each class, it’s time to simulate this example with code. The code for this example and all following examples will be in Python 3.

Code

The Item class has only one method ‘prepare’, which is common across all it’s derived classes. Now let us construct the menu items from this superclass. We will construct child class to encapsulate the roti items which can be inherited by the child classes representing the different varieties of roti.

As you can see above, we have constructed the menu items hierarchy to represent different types of roti dishes. The same procedure can be followed for the rest of the items as well. Now, let us move on to the Meal class.

Finally, let’s bring all of this together in the MealKitchen class

There you go ! We have successfully simulated a restaurant scenario using the factory method. The complete code for this example can be found here. In the next blogpost, we will discuss the abstract factory method in detail.

--

--

Vijayasri Iyer

Machine Learning Scientist @ Pi School. MTech in AI. Musician. Yoga Instructor. Learnaholic. I write about anything that makes me curious.