A comprehensive, production-ready collection of Gang of Four (GoF) design patterns implemented in modern, idiomatic Python. This repository serves as a valuable resource for developers looking to understand, learn, and apply design patterns to build robust, scalable, and maintainable software.
Inspired by the highly-regarded java-design-patterns project, this repository aims to provide the Python community with a similarly high-quality educational tool, focusing on clarity and practical application.
This project is built upon a set of core principles to ensure it is a high-quality, trustworthy resource for the Python community.
- Clarity and Readability: Code is written to be understood, not just to work. We prioritize clear variable names, simple logic, and comprehensive comments.
- Pythonic Implementation: Patterns are adapted to leverage Python's unique features (like decorators, context managers, and first-class functions), not just translated from other languages.
- Production-Ready: Implementations are robust, type-hinted, and suitable for real-world applications. Thread-safety and performance are considered where applicable.
- Comprehensive Documentation: Each pattern is thoroughly documented to explain its intent, structure, trade-offs, and real-world use cases.
- Thorough Testing: A full test suite with high coverage ensures correctness, reliability, and adherence to the pattern's principles.
Get up and running in a few simple steps.
# 1. Clone the repository
git clone https://github.com/y-haviv/python-design-patterns.git
cd python-design-patterns
# 2. Set up a virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Run all tests to verify the setup
pytest# Import any pattern
from creational.singleton import Singleton
from structural.adapter import Adapter, Target
from behavioral.observer import Subject, Observer
# Use in your code
my_singleton = Singleton()
my_adapter = Adapter(adaptee)
my_subject = Subject()
my_subject.attach(my_observer)Each pattern directory has a comprehensive README.md:
# Read about any pattern
cat creational/singleton/README.md
cat structural/adapter/README.md
cat behavioral/observer/README.md- Singleton - Single instance, global access
- Factory Method - Deferred instantiation
- Abstract Factory - Family of objects
- Builder - Complex object construction
- Prototype - Clone existing objects
- Adapter - Interface compatibility
- Bridge - Abstraction-implementation separation
- Composite - Tree composition
- Decorator - Dynamic enhancement
- Facade - Simplified interface
- Flyweight - Object sharing
- Proxy - Access control
- Command - Request encapsulation
- Iterator - Sequential access
- Mediator - Centralized communication
- Memento - State preservation
- Observer - One-to-many notification
- State - State-dependent behavior
- Strategy - Algorithm encapsulation
- Visitor - Object tree traversal
- Start with Singleton - simplest pattern
- Move to Factory Method - common foundation
- Try Observer - practical and powerful
- Learn Decorator - shows composition benefits
- Study Strategy - runtime algorithm selection
- Master Composite - tree structures
- Explore Adapter - integration problems
- Understand Bridge - abstraction separation
- Deep dive Memento - state management complexity
- Implement Mediator - coordination patterns
- Use Visitor - advanced traversal
- Optimize with Flyweight - memory efficiency
These patterns are used everywhere:
- Web Frameworks: Django, Flask, FastAPI
- Data Processing: pandas, NumPy, scikit-learn
- Testing Frameworks: pytest, unittest, Mock
- Databases: SQLAlchemy, tortoise-orm
- Async Libraries: asyncio, aiohttp
See specific implementations for real use cases!
# Type hints
def process_data(items: List[str], count: int) -> Dict[str, Any]:
...
# Comprehensive docstrings
def method(param: str) -> None:
"""
Do something helpful.
Args:
param: Description of param
Returns:
Description of return value
Raises:
ValueError: When something is invalid
"""
pass
# Clean, readable code
name = TypedName("valid_identifier")
factory = PatternFactory()
result = factory.create(config)# Run tests with coverage
pytest --cov=. --cov-report=html
# All patterns have:
# - Unit tests (100% coverage)
# - Integration tests (real-world scenarios)
# - Edge case tests (error handling)
# - Performance tests (optimization checks)This is an open-source project
- Fix bugs - Found an issue? Open a PR!
- Improve documentation - Clearer explanations help everyone
- Add examples - Show real-world usage
- Optimize performance - Make pattern implementations faster
- Add tests - Better coverage = better code
See CONTRIBUTING.md for detailed guidelines.
- Getting Started - Setup and first steps
- Architecture Guide - Project structure
- Development Guide - How to contribute
- Patterns Overview - Deep dive comparison
- FAQ - Common questions answered
- Python: 3.9 or higher
- Dependencies: None (core library) - see optionals in requirements.txt
- Testing: pytest
This project is licensed under the MIT License - see LICENSE for details.
The MIT License is ideal for educational projects because it:
- Allows commercial use
- Permits modification and distribution
- Requires only attribution
- Is simple and permissive
- π Check the FAQ
- π Report a bug
- π¬ Start a discussion
- Gang of Four - Original design patterns from their seminal work
- java-design-patterns - Inspiration for this project structure
- Python Community - For the amazing ecosystem
- Pattern implementation guides (video tutorials)
- Interactive pattern browser (web app)
- Design patterns converter (e.g., Java β Python)
- Performance benchmarks dashboard
- Anti-patterns examples and solutions
- Design pattern quiz/assessment tool
| Metric | Count |
|---|---|
| Total Patterns | 21 |
| Implementation Files | 84+ |
| Test Cases | 200+ |
| Code Examples | 50+ |
| Documentation | 5,000+ lines |
| Test Coverage | ~95% |
- Clone the repo -
git clone ... - Read a pattern README - Understand the concept
- Study pattern.py - Learn the implementation
- Check real_world_example.py - See practical usage
- Run and modify tests - Experiment and learn
- Apply to your project - Use what you learned
Ready to master design patterns? Start with Singleton!
β If you find this helpful, please give it a star!
Report Bug β’ Request Feature β’ Contribute