Introduction
Design patterns are reusable solutions to common software design problems. They represent best practices evolved over time and help developers create maintainable, flexible, and scalable code. Understanding these patterns is essential for writing professional-quality Python applications.
Singleton Pattern
The Singleton pattern ensures a class has only one instance and provides a global point of access to it.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # True
Factory Pattern
The Factory pattern provides an interface for creating objects without specifying their exact classes.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
raise ValueError("Unknown animal type")
animal = AnimalFactory.create_animal("dog")
print(animal.speak()) # Woof!
Observer Pattern
The Observer pattern defines a one-to-many dependency between objects so when one changes state, all dependents are notified.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update(self)
class Observer:
def update(self, subject):
print(f"Observer notified of state change")
subject = Subject()
observer = Observer()
subject.attach(observer)
subject.notify()
Practice Problems
- Implement a Singleton class that tracks the number of instances created.
- Create a factory that produces different shape objects (Circle, Rectangle, Triangle).
- Build an observer system where a weather station notifies multiple displays when temperature changes.
- Implement a thread-safe Singleton using the threading module.
- Create a factory method pattern for different payment processors (CreditCard, PayPal, BankTransfer).