Python Design Pattern — Part I: Creational Design Pattern

Vahid Naghshin
CodeX
Published in
5 min readJul 25, 2021

Creational design patterns provide diverse object creation mechanisms, which boost flexibility and reuse of existing code.

If we try to define the design pattern in the context of software engineering, nothing better than Wikipedia can give a straight definition:

In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design.

There are three main categories in design pattern context: creational, structural, behavioral patterns. Creational design patterns mostly deal with various object creation mechanisms, which increase flexibility and reuse of existing code. Structural patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects. In this short article, we will walk you through the creational design pattern with some examples from Python.

As mentioned before, the creational design pattern provides various object creation mechanism which improves the code flexibility for possible future reuse. This also facilitates the communication between developers in order to collaborate more efficiently in a highly dynamic environment.

The creational design pattern consists mainly of five useful components in handling the object creation:

  • Factory method
  • Abstract Factory
  • Builder
  • Prototype
  • Singleton

In the following, we will go through each of these and present you with some Python examples.

Factory Method

The factory method is a creational design pattern that provides an interface for a superclass to call and create an object with the type of the object created can be controlled and determined by the subclass.

Problem

Imagine that you have a pet management application. Initially, you only have one pet class called dog. So the bulk of your code lives inside the Dogclass. Later, come up with a situation that needs to add more classes such as cat. Adding Cat into the app would require making changes to the entire codebase. Moreover, this issue will exacerbate if more classes are added.

Solution

The factory method allows you to create an object from another object. It is construction calls (using the new operator) with calls to a special factory method. Please note that in order to use the factory method it is better that all the classes, to be called, share the same method and attributes.

Python Example code

This is Python Example for factory method. As you can see, we have two different classes, dog and cat . Two classes can be called from get_pet factory class.

Abstract Factory

The abstract factory lets you create a family of related objects without specifying the concrete class. In other words, you can call the families of class just via one single interface. It also can be used when you want to create a bunch of related operation.

Problem

Imagine you want to create a pet store that accommodate the pet’s name, pet’s food, and its sound. You need a way to create individual furniture objects so that they match other objects of the same family.

Solution

You can create and call all these classes through a superclass abstract factory. You actually create the related classes individually and call them through a common interface.

Python Example Code

Here is the Python snippet that uses abstract factory to create two classes. Through petfactory class we create the interface to create the pet object. Next, we use petStore to access the object’s name, food and the sounding.

Builder

The builder as a creational design pattern lets you construct a complex system step by step. The pattern lets you construct different objects, each out of subset of already-built components.

Problem

Imagine a complex object that requires laborious, step-by-step initialization of many fields and nested objects. In order to construct any single objects with any set of available components you need to write so many classes each corresponding to a specific set.

Solution

The solution is that you can load off the assembly task to a separate class called builder. The builder’s responsibility is to assembly the required set of steps dictates usually by director. However, existence of director is not necessary, but it will improve readability and modularity.

Python Example

Here, we would like to create two cars with different options: one with horn and the other without. We add options through engine_builder class inherited from superclass builder . The engine_builder includes all options construction dictated by builder. The director includes two methods corresponding to two different options. The way that director dictates the steps, the builder builds the objects.

Prototype

Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.

Problem

Say you have an object, and you want to create an exact copy of it. How would you do it? First, you have to create a new object of the same class. Then you have to go through all the fields of the original object and copy their values over to the new object [1]. There is a catch with this method. Not all attributes and methods can be seen outside of an object and might be private.

Solution

The Prototype pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning. Usually, it is identified by the clone method.

Python Example

Here, we’d like to clone a car object out of another created car. To this end, we will first register the class and then clone it into another object with different name using the clone method.

Singleton

Singleton allows to be sure that there is only one single instantiation of one class and it is accessible globally.

Problem

The singleton design pattern is designed to solve two common problem. One is that we make sure that there is only one single instance of a given class. Why do we care? In some applications, we have one shared file such as database that is shared between different classes. We want to be sure that each class has the same copy of the database. The second problem that singleton tries to solve is global access which makes a class accessible by any class from anywhere in the program.

Python Example

Here, we have one dictionary which we would like to be edited by some point at time. We see that at first hand, the file includes John="Paid and then another element is added. Now, the content is changed to {‘John’: ‘Paid’, ‘Lucy’: ‘NOT Paid’}.

This concludes the article :)

Reference

[1] https://refactoring.guru/design-patterns/prototype

--

--

Vahid Naghshin
CodeX
Writer for

Technology enthusiast, Futuristic, Telecommunications, Machine learning and AI savvy, work at Dolby Inc.