Design Patterns
Summary
GoF patterns, examples, and use cases. From creational to behavioral patterns.
Creational Patterns
Singleton
Ensure a class has only one instance.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instanceFactory Method
Create objects without specifying exact class.
def create_animal(type):
if type == "dog":
return Dog()
elif type == "cat":
return Cat()Builder
Construct complex objects step by step.
builder = ComputerBuilder()
computer = builder.add_cpu("Intel")
.add_ram("16GB")
.build()Structural Patterns
Adapter
Convert interface of class into another interface.
class Adapter:
def __init__(self, obj):
self.obj = obj
def adapted_method(self):
return self.obj.original_method()Decorator
Add responsibilities to objects dynamically.
@decorator
def function():
pass
# Or class-based
class Decorator:
def __init__(self, wrapped):
self.wrapped = wrapped
def __call__(self):
return self.wrapped()Behavioral Patterns
Observer
Define one-to-many dependency between objects.
class Observer:
def update(self, subject):
pass
class Subject:
def attach(self, observer):
self.observers.append(observer)
def notify(self):
for obs in self.observers:
obs.update(self)Strategy
Define family of algorithms, encapsulate each.
class Context:
def __init__(self, strategy):
self.strategy = strategy
def execute(self, data):
return self.strategy.execute(data)Download
Print this page or save as PDF for quick reference.
Tip: Use Ctrl+P (Cmd+P on Mac) to print or save as PDF.