~/Common Design Patterns in Python

Oct 12, 2022


Design patterns in Python are reusable solutions for common coding problems.

Singleton Pattern
Ensures only one instance of a class exists.

1
2
3
4
5
6
class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

Details

Factory Pattern
Creates objects without specifying the exact class.

1
2
3
4
5
6
class AnimalFactory:
    def create_animal(self, animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()

Details

Observer Pattern
Notifies dependents about state changes.

1
2
3
4
5
6
7
8
class Subject:
    def __init__(self):
        self.observers = []
    def register(self, obs):
        self.observers.append(obs)
    def notify(self):
        for o in self.observers:
            o.update()

Details

Use these patterns to write modular, maintainable code.

Tags: [python] [designpatterns]