Wednesday, April 5, 2023

Design Patterns in Python

1. Creational Design Patterns

Factory Method: The constructor stores a dictionary. A Factory method gets the state value from this dictionary passing the key as String.

Abstract Factory method: Here, the constructor should return objects of other classes based on whatever key is passed.

Singleton: A class variable is initialized by the constructor and a static getInstance() method returns that variable every time an object creation is initiated.

Prototype: This uses copy.copy(obj) or copy.deepcopy(obj) to create objects.

Builder: A builder class is used to work on different objects which are called one after the other.


2. Structural Design Patterns

Adapter: An actual object is passed to an adapter constructor to modify it for further operations.

Bridge: A composition (has-a relationship) is used where a class has another class as its instance variable initialized through constructor.

Composite: This ensures that a hierarchy is defined in a tree model by adding leaf classes to a list type instance variable of the composite class.

Decorator:  Each child class adds extra behaviour to parent as,

class FirstConcreteHandler(AbstractHandler):

class SecondConcreteHandler(AbstractHandler):

class ThirdConcreteHandler(AbstractHandler):

self.handler = FirstConcreteHandler(SecondConcreteHandler(ThirdConcreteHandler()))


3. Behavioural Design Patterns

Observer: This ensures that all Observer classes are updated when there is a change.A common class has instance variables of all Observer classes. It also has methods to update the Observers whenever its onchange() method is called.

No comments: