Personal notes, examples, and implementations for learning Python Design Patterns (Gang of Four + Pythonic twists).
This repository contains clean, well-documented implementations of classic design patterns with Python 3.10+ features, comprehensive examples, and practical use cases.
- Overview
- Project Structure
- Implemented Patterns
- Installation & Setup
- Usage
- Running Examples
- Pattern Details
- Code Quality
- Contributing
- License
This project provides a comprehensive learning resource for understanding and implementing design patterns in Python. Each pattern includes:
- Clean, readable code following PEP 8 standards
- Comprehensive docstrings with examples and explanations
- Type hints for better code documentation and IDE support
- Error handling and edge case management
- Thread-safe implementations where applicable
- Practical examples demonstrating real-world usage
- Unit tests to verify correctness (when applicable)
python-design-patterns-learning/
βββ design_patterns/
β βββ __init__.py
β βββ creational/
β β βββ __init__.py
β β βββ singleton.py
β β βββ factory_method.py
β βββ structural/
β β βββ __init__.py
β βββ behavioral/
β βββ __init__.py
β βββ observer.py
βββ examples.py
βββ README.md
- Singleton - Ensures a class has only one instance
- Factory Method - Creates objects without specifying exact classes
Coming soon in future iterations
- Observer - Defines subscription mechanism for object notifications
- Python 3.10 or higher
- No external dependencies required (uses only Python standard library)
- Clone the repository:
git clone https://github.com/MachariaP/python-design-patterns-learning.git
cd python-design-patterns-learning
- Verify Python version:
python --version # Should be 3.10+
# Using Singleton Pattern
from design_patterns.creational import Singleton, SingletonMeta
class DatabaseManager(metaclass=SingletonMeta):
def __init__(self):
self.connection = "Connected to database"
db1 = DatabaseManager()
db2 = DatabaseManager()
assert db1 is db2 # True - same instance
# Using Factory Method Pattern
from design_patterns.creational import ProductFactory, ConcreteProductA
factory = ProductFactory()
factory.register_product("typeA", ConcreteProductA)
product = factory.create_product("typeA", name="My Product")
print(product.operation())
# Using Observer Pattern
from design_patterns.behavioral import ConcreteSubject, ConcreteObserver
subject = ConcreteSubject()
observer = ConcreteObserver("Observer1")
subject.attach(observer)
subject.state = "New State" # Observer will be notified
# Import all creational patterns
from design_patterns import creational
# Import specific pattern categories
from design_patterns import behavioral
python examples.py
# Singleton Pattern
python -m design_patterns.creational.singleton
# Factory Method Pattern
python -m design_patterns.creational.factory_method
# Observer Pattern
python -m design_patterns.behavioral.observer
This repository now includes extensive documentation covering design patterns theory, implementation, and real-world applications:
- π Complete Documentation - Main documentation hub with full navigation
- π What are Design Patterns? - Fundamental concepts and why patterns matter
- π Pattern Classifications - The three main categories with detailed explanations
- π― Singleton Pattern - Ensure single instance with comprehensive examples
- π Factory Method Pattern - Object creation without specifying classes
- π Observer Pattern - Subscription mechanism for notifications
- π Web Application Examples - Patterns in web development
- ποΈ System Design Examples - Distributed systems and microservices
- π’ Enterprise Application Patterns - Complex business applications
Singleton Pattern:
- Thread-safe metaclass and inheritance implementations
- Real-world examples (config management, connection pools, logging)
- Performance considerations and testing strategies
- Common pitfalls and best practices
Factory Method Pattern:
- Abstract base classes with comprehensive type hints
- Dynamic product registration system
- API response factories and middleware creation examples
- Database driver and UI component factories
Observer Pattern:
- Thread-safe implementation with weak references
- Event-driven architecture examples
- Real-time notification systems
- MVC pattern implementation with automatic cleanup
This project follows Python best practices:
- PEP 8 compliance for code style
- Type hints throughout the codebase
- Comprehensive docstrings with examples
- Error handling with appropriate exceptions
- Thread safety for concurrent usage
- Memory management with weak references where appropriate
- Modular design for easy extension and reuse
# Example of code style used throughout the project
from typing import Any, Dict, List, Optional
from abc import ABC, abstractmethod
class ExampleClass(ABC):
"""
Example class demonstrating the code style used in this project.
This class shows proper docstring format, type hints, and
error handling patterns used throughout the codebase.
"""
def __init__(self, name: str) -> None:
"""
Initialize the example class.
Args:
name: The name identifier for this instance
Raises:
ValueError: If name is empty or invalid
"""
if not name or not isinstance(name, str):
raise ValueError("Name must be a non-empty string")
self._name = name
@abstractmethod
def process(self, data: Any) -> Dict[str, Any]:
"""
Abstract method that subclasses must implement.
Args:
data: Input data to process
Returns:
Dictionary containing processed results
Raises:
NotImplementedError: If not implemented by subclass
"""
pass
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature-name
- Follow the coding standards established in the project
- Add comprehensive tests for new patterns
- Update documentation as needed
- Submit a pull request
When adding new design patterns:
- Place them in the appropriate category folder
- Follow the established code style and documentation format
- Include comprehensive examples and error handling
- Add the pattern to the relevant
__init__.py
file - Update this README with pattern information
This project is open source and available under the MIT License.
- Gang of Four - For the original Design Patterns book
- Python Community - For excellent documentation and best practices
- Contributors - For improvements and feedback
Happy Learning! π
For questions, suggestions, or issues, please open an issue on GitHub.