A comprehensive collection of design patterns implemented in Python to demonstrate software design principles and best practices.
This repository provides practical implementations of classic design patterns in Python. Each pattern is implemented as a standalone example file, making it easy to understand and apply these concepts in your own projects.
The repository is organized based on the three main categories of design patterns:
Patterns that deal with object creation mechanisms:
- Abstract Factory - Provides an interface for creating families of related objects
- Builder - Separates object construction from its representation
- Factory - Creates objects without specifying the exact class to create
- Prototype - Creates new objects by copying existing ones
- Singleton - Ensures a class has only one instance
Patterns that focus on object composition:
- Adapter - Allows incompatible interfaces to work together
- Bridge - Separates an abstraction from its implementation
- Composite - Composes objects into tree structures
- Decorator - Adds responsibilities to objects dynamically
- Proxy - Provides a surrogate for another object
Patterns that focus on communication between objects:
- Chain of Responsibility - Passes requests along a chain of handlers
- Iterator - Accesses elements of a collection sequentially
- Observer - Defines a one-to-many dependency between objects
- Strategy - Defines a family of algorithms and makes them interchangeable
- Visitor - Separates algorithms from the objects on which they operate
# Import the Singleton class
# You can directly use the singleton.py file
# First instance
singleton1 = Singleton()
singleton1.value = 10
# Second instance (same object)
singleton2 = Singleton()
# Test if both variables reference the same object
print(f"Singleton1 value: {singleton1.value}") # Output: 10
print(f"Singleton2 value: {singleton2.value}") # Output: 10
print(f"Same instance: {singleton1 is singleton2}") # Output: True
# Changing value in one instance affects the other
singleton2.value = 20
print(f"Singleton1 value after change: {singleton1.value}") # Output: 20
# Import from strategy.py
# context = Context()
# context.set_strategy(ConcreteStrategyA())
# result = context.execute_strategy()
Each pattern file includes:
- Brief explanation of the pattern
- Implementation example
- Use cases when the pattern is applicable
Contributions are welcome! If you'd like to add new patterns or improve existing ones:
- Fork the repository
- Create your feature branch (
git checkout -b feature/new-pattern
) - Commit your changes (
git commit -m 'Add some pattern'
) - Push to the branch (
git push origin feature/new-pattern
) - Open a Pull Request
Created and maintained by zalhamami.