Python Design Patterns

Reading time ~1 minute

Factory DP : This is an design pattern in which we can create a interface factory (method) to instantiate the objects of classes. This helps in instantialting the right kind of object.

In the example below, we have 2 classes for Cars and Truck, in which we have the methods that return the no of tyres in each type of Vehicle. Using factory pattern we can identify the correct class to instantiate based on the parameters invoked in the factory method.

class Car:

	def __init__(self, type):
		self._type = type

	def no_of_tyres(self):
		return 4

class Truck:

	def __init__(self, type):
    		self._type = type

	def no_of_tyres(self):
		return 6

def get_auto(auto_type="car"):

	"""The factory method"""

	autos = dict(car=Car("Audi"), truck=Truck("Volvo"))

	return autos[auto_type]

d = get_auto("car")


c = get_auto("truck")


Abstract Factory DP : In the last example we have seen that we can create a factory for known classes. In Abstract factory we don’t have this information (classes) till runtime.

To implement this we will create Abstact factory and concrete factory as below:

Python GUI Development: Tkinter

[Main Course Link]( Series is a part of [30 Days of Learning]...… Continue reading

Effective Note Taking

Published on June 20, 2021

Python Web Scraping

Published on June 19, 2021