Skip to content

MachariaP/python-design-patterns-learning

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Python Design Patterns Learning

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.

πŸ“‹ Table of Contents

🎯 Overview

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)

πŸ“ Project Structure

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

πŸ”§ Implemented Patterns

Creational Patterns

  • Singleton - Ensures a class has only one instance
  • Factory Method - Creates objects without specifying exact classes

Structural Patterns

Coming soon in future iterations

Behavioral Patterns

  • Observer - Defines subscription mechanism for object notifications

πŸš€ Installation & Setup

Prerequisites

  • Python 3.10 or higher
  • No external dependencies required (uses only Python standard library)

Setup

  1. Clone the repository:
git clone https://github.com/MachariaP/python-design-patterns-learning.git
cd python-design-patterns-learning
  1. Verify Python version:
python --version  # Should be 3.10+

πŸ’» Usage

Import and Use Individual Patterns

# 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 Complete Modules

# Import all creational patterns
from design_patterns import creational

# Import specific pattern categories
from design_patterns import behavioral

πŸƒβ€β™‚οΈ Running Examples

Run All Examples

python examples.py

Run Individual Pattern Examples

# 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

πŸ“š Comprehensive Documentation

This repository now includes extensive documentation covering design patterns theory, implementation, and real-world applications:

πŸ“– Core Documentation

πŸ› οΈ Implemented Patterns

🌍 Real-World Examples

🎯 Pattern Features in This Repository

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

πŸ›  Code Quality

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

Code Style

# 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

🀝 Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Follow the coding standards established in the project
  4. Add comprehensive tests for new patterns
  5. Update documentation as needed
  6. Submit a pull request

Adding New Patterns

When adding new design patterns:

  1. Place them in the appropriate category folder
  2. Follow the established code style and documentation format
  3. Include comprehensive examples and error handling
  4. Add the pattern to the relevant __init__.py file
  5. Update this README with pattern information

πŸ“„ License

This project is open source and available under the MIT License.

πŸ™ Acknowledgments

  • 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.

About

Personal notes, examples, and implementations for learning Python Design Patterns (GoF + Pythonic twists).

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages