Example code from Head First Design Patterns second edition translated to python to help me understand and memorise the patterns.
I have added examples of pattern usage in the Python standard library and pypi - I am starting to see patterns everywhere!
Note I am aiming for a reasonably literal translation whilst trying to make the code a little more pythonic by, e.g. using python conventions for
ClassNames
andmethod_names
and putting all of the code in a single file where it makes sense to do so.
- Strategy
- Observer
- Decorator
- Factory Method
- Simple Factory
- Abstract Factory
- Singleton
- Command
- Adapter
- Façade
- Template Method
- Iterator
- Composite
- State
- Proxy
- Model View Controller (MVC)
From the book 📖:
package headfirst.designpatterns.strategy;
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() {
}
public void setFlyBehavior(FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
abstract void display();
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
public void swim() {
System.out.println("All ducks float, even decoys!");
}
}
From this repository :
class Duck():
_fly_behavior = None
_quack_behavior = None
def set_fly_behavior(self, fly_behavior):
self._fly_behavior = fly_behavior
def set_quack_behavior(self, quack_behavior):
self._quack_behavior = quack_behavior
def display(self):
raise NotImplementedError
def perform_fly(self):
self._fly_behavior.fly()
def perform_quack(self):
self._quack_behavior.quack()
def swim(self):
print("All ducks float, even decoys! 〰🦆〰")
- Encapsulate what varies
- Open-Closed Principle: Open for extension, closed for modification
- Program to an interface, not to an implementation
- Favour composition over inheritence
- Dependency Inversion Principle
- Depend upon abstractions
- The Hollywood Principle : "Don't call us, we'll call you"
- One Class, One Responsibility Principle
- Single Responsibility Principle
- Principle of Least Knowledge
I started to work on the MVC pattern here but have a small complete MVC implementation in JavaScript in another repo.