Advanced Python Patterns
Singleton, factory, observer, and other design patterns.
Overview
Implement common design patterns.
Singleton Pattern
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
Factory Pattern
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create(animal_type):
animals = {"dog": Dog, "cat": Cat}
return animals.get(animal_type)()
dog = AnimalFactory.create("dog")
print(dog.speak()) # Woof!
Observer Pattern
class EventSystem:
def __init__(self):
self.listeners = {}
def subscribe(self, event, callback):
if event not in self.listeners:
self.listeners[event] = []
self.listeners[event].append(callback)
def emit(self, event, data):
for callback in self.listeners.get(event, []):
callback(data)
system = EventSystem()
system.subscribe("message", lambda msg: print(f"Received: {msg}"))
system.emit("message", "Hello!")
Practice
Implement a command pattern for a text editor.