{"id":26186731,"url":"https://github.com/saikotek/python-design-patterns","last_synced_at":"2026-03-08T14:31:37.966Z","repository":{"id":246277657,"uuid":"818058491","full_name":"saikotek/python-design-patterns","owner":"saikotek","description":"Practical Design Patterns in Python. This project attempts to demonstrate the implementation of various design patterns in real-world use cases using protocols.","archived":false,"fork":false,"pushed_at":"2025-03-16T22:39:44.000Z","size":135,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-07T01:41:32.467Z","etag":null,"topics":["design","design-patterns","patterns","python","pythonic"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/saikotek.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-21T02:37:28.000Z","updated_at":"2025-03-16T22:39:48.000Z","dependencies_parsed_at":"2024-06-27T01:02:42.078Z","dependency_job_id":"9a0e7cef-db0c-4b7e-b9e8-b494ed4f20b8","html_url":"https://github.com/saikotek/python-design-patterns","commit_stats":null,"previous_names":["saikotek/python-design-patterns"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saikotek%2Fpython-design-patterns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saikotek%2Fpython-design-patterns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saikotek%2Fpython-design-patterns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/saikotek%2Fpython-design-patterns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/saikotek","download_url":"https://codeload.github.com/saikotek/python-design-patterns/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248986265,"owners_count":21194022,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["design","design-patterns","patterns","python","pythonic"],"created_at":"2025-03-11T23:34:06.234Z","updated_at":"2026-03-08T14:31:37.937Z","avatar_url":"https://github.com/saikotek.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Practical Design Patterns in Python\nThis project demonstrates the implementation of various design patterns in Python.\nEach design pattern is implemented conceptually in a file named `concept.py` and practical examples are provided in files prefixed with `ex_`.\nThis way you can see how to apply the design pattern in real-world scenarios.\n\nI attempted to use modern Python features and best practices in the examples, such as:\n- Type hints\n- Dataclasses\n- Protocols\n- Alternative approaches to design patterns such as function decorators\n\nThis repository serves as a comprehensive reference for understanding and implementing design patterns in Python.\n## What are Design Patterns?\nDesign patterns are proven solutions to common software design problems. They provide a template for writing code that is maintainable, reusable, and scalable. \nThis project covers a wide range of design patterns, traditionally divided into three categories: creational, structural, and behavioral.\n\nMost of them are from the book \"Design Patterns: Elements of Reusable Object-Oriented Software\" by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.\n\n## Installing\nRequired Python \u003e= 3.8\u003cbr/\u003e\nCreate virtual environment and install dependencies:\n```\npy -m venv venv\npip install -r requirements.txt\n```\n\n## List of Design Patterns\nEach design pattern has at least two scripts:\n  - `concept.py` - conceptual implementation\n  - `ex_{script}.py` - example real-world scenario\n\nWe'll start with classic design patterns and then move on to additional patterns.\nClassic design patterns are divided into three categories: creational, structural, and behavioral.\n### Creational Patterns\n- **Abstract Factory**\n  - `concept.py` - Intent: Lets you create families of related objects without specifying their concrete implementations.\n  - `ex_gui.py` - Example: Demonstrates creating families of related UI elements for Windows and Mac OS.\n\n- **Builder**\n  - `concept.py` - Intent: Separate the construction of a complex object from its representation so that the same construction process can create different representations.\n  - `ex_computer.py` - Example: Computer Builder with concrete builder classes for gaming and office computers.\n  - `ex_computer_fluent.py` - Example: Fluent Builder for building computers with different specifications.\n\n- **Factory Method**\n  - `concept.py` - Intent: Lets you create objects without specifying the exact class to create, using factory methods instead of constructors.\n  - `ex_notifications.py` - Example: Notifications system that creates different types of notifications.\n\n- **Prototype**\n  - `concept.py` - Intent: Allows cloning objects without coupling to their specific classes using shallow and deep copying.\n  - `ex_documents.py` - Example: Document cloning system.\n\n- **Singleton**\n  - `concept.py` - Intent: Ensures that a class has only one instance while providing a global access point to this instance.\n  - `concept_threadsafe.py` - Intent: Thread-safe implementation of the Singleton pattern.\n  - `ex_configuration.py` - Example: Configuration class that stores application settings as a singleton.\n\n### Structural Patterns\n- **Adapter**\n  - `concept_class_adapter.py` - Intent: Converts the interface of a class into another interface clients expect using multiple inheritance.\n  - `concept_object_adapter.py` - Intent: Converts the interface of a class into another interface clients expect using composition.\n  - `ex_xml_to_json_adapter.py` - Example: Adapts XML data processor to work with a JSON analytics system.\n\n- **Bridge**\n  - `concept.py` - Intent: Decouples an abstraction from its implementation so that the two can vary independently.\n  - `ex_databases.py` - Example: Refined abstractions of Database for different (SQLite, Postgres) implementations.\n  - `ex_gui.py` - Example: Tkinter GUI application with theme implementations (Light and Dark) bridged with applications.\n\n- **Composite**\n  - `concept.py` - Intent: Composes objects into tree structures to represent part-whole hierarchies, allowing clients to treat individual objects and compositions uniformly.\n  - `ex_file_system.py` - Example: Working with files and directories through a composite structure.\n\n- **Decorator**\n  - **Class Decorators**\n    - `concept.py` - Intent: Python class-based decorators that modify the behavior of functions or methods.\n    - `ex_data_access.py` - Example: Data access control with class decorators for role checking and caching.\n  - **Classic Decorators**\n    - `concept.py` - Intent: Adds behavior to objects dynamically without affecting other instances of the same class.\n    - `ex_data_access.py` - Example: Data access service with access control and caching decorators.\n    - `ex_data_handler.py` - Example: Data handler with encryption and compression decorators.\n    - `ex_document_processor.py` - Example: Document processor with spell check and grammar check decorators.\n  - **Function Decorators**\n    - `concept.py` - Intent: Python function decorators that modify the behavior of functions or methods.\n    - `ex_access_control.py` - Example: Access control decorator for functions.\n    - `ex_caching.py` - Example: Caching decorator for functions.\n    - `ex_logging.py` - Example: Logging decorator for functions.\n\n- **Facade**\n  - `concept.py` - Intent: Provides a simplified interface to a complex subsystem of classes.\n  - `ex_third_party_lib.py` - Example: Facade for a third-party email library.\n\n- **Flyweight**\n  - `concept.py` - Intent: Minimizes memory usage by sharing common state between multiple objects.\n  - `ex_chess.py` - Example: Chess pieces factory reusing shared pieces.\n\n- **Proxy**\n  - `concept.py` - Intent: Provides a surrogate or placeholder for another object to control access to it.\n  - `ex_caching_proxy.py` - Example: Caching proxy for expensive operations.\n  - `ex_logging_proxy.py` - Example: Logging proxy that logs each request to the original object.\n  - `ex_protection_proxy.py` - Example: Protection proxy controlling access based on user roles.\n  - `ex_protection_proxy_decorator.py` - Example: Protection proxy using decorators.\n  - `ex_smart_reference_proxy.py` - Example: Smart reference proxy.\n  - `ex_virtual_proxy.py` - Example: Virtual proxy for lazy initialization of expensive objects.\n\n### Behavioral Patterns\n- **Chain of Responsibility**\n  - `concept.py` - Intent: Passes a request along a chain of handlers, with each handler deciding to process or pass it along.\n  - `ex_gui.py` - Example: GUI components with contextual help system.\n\n- **Command**\n  - `concept.py` - Intent: Turns requests into stand-alone objects for parameterization, queuing, and supporting undoable operations.\n  - `ex_editor.py` - Example: Text editor with undo functionality.\n\n- **Iterator**\n  - `concept.py` - Intent: Provides a way to traverse elements of a collection without exposing its underlying representation.\n  - `ex_graph.py` - Example: Graph traversal using breadth-first and depth-first search.\n  - `ex_inventory.py` - Example: Inventory traversal system.\n  - `ex_tree.py` - Example: Tree traversal implementation.\n\n- **Mediator**\n  - `concept.py` - Intent: Reduces dependencies between objects by forcing them to communicate via a mediator object.\n  - `ex_chatroom.py` - Example: Chat room using mediator to notify users of messages.\n  - `ex_stock_market.py` - Example: Stock market communication system.\n  - `ex_ui_components.py` - Example: UI components coordinated by a mediator.\n\n- **Memento**\n  - `concept.py` - Intent: Captures an object's internal state to restore it later without exposing its structure.\n  - `ex_game_state.py` - Example: Saving and restoring game states.\n  - `ex_transactional_db.py` - Example: Transactional database with save and restore capabilities.\n\n- **Observer**\n  - `concept.py` - Intent: Defines a one-to-many relationship so when one object changes state, all dependents are notified.\n  - `concept_distributed.py` - Intent: Distributed observer pattern allowing components to act as both publishers and subscribers.\n  - `ex_smart_home.py` - Example: Home automation system with devices publishing and subscribing to events.\n  - `ex_stock_market.py` - Example: Stock market monitoring where clients subscribe to price updates.\n\n- **State**\n  - `concept.py` - Intent: Allows an object to alter its behavior when its internal state changes.\n  - `ex_traffic_lights_enum.py` - Example: Traffic lights using simple enum-based state machine.\n  - `ex_traffic_lights_sm_library.py` - Example: Traffic lights using a third-party state machine library.\n  - `ex_traffic_lights_state.py` - Example: Traffic lights using class-based state pattern implementation.\n\n- **Strategy**\n  - `concept.py` - Intent: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.\n  - `ex_payment_processor.py` - Example: Payment strategies for an online store.\n  - `ex_text_formatter.py` - Example: Text formatting strategies for a document editor.\n\n- **Template Method**\n  - `concept.py` - Intent: Defines the skeleton of an algorithm allowing subclasses to override specific steps without changing structure.\n  - `ex_data_pipeline.py` - Example: Data processing pipeline implementation.\n\n- **Visitor**\n  - `concept.py` - Intent: Separates algorithms from the objects they operate on using double dispatch.\n  - `ex_file_visitor.py` - Example: File system visitor performing operations on different file types.\n\n### Additional Patterns\n- **Repository**\n  - `concept.py` - Intent: Mediates between the domain and data mapping layers using a collection-like interface for accessing data.\n  - `ex_sqlite_repository.py` - Example: SQLite repository for storing and retrieving data.\n\n- **Specification**\n  - `concept.py` - Intent: Creates complex filtering logic by combining simple rules.\n  - `ex_ecommerce.py` - Example: E-commerce product filtering using combined specifications.\n\n- **Context Manager**\n  - `concept.py` - Intent: Simplifies resource management by providing setup and teardown actions.\n  - `ex_timing.py` - Example: Timing context manager for measuring execution time of inner block.\n  - `ex_database_connection.py` - Example: Database connection context manager to properly save changes and close connections.\n\n## Remarks\n- Most of the examples don't do the real job, they just show how you'd leverage the design pattern in certain use case.\u003cbr/\u003e\nBut there are some examples in which I've attempted to do the real job as in [bridge pattern database example](https://github.com/saikotek/python-design-patterns/blob/main/src/bridge/ex_databases.py) that uses Testcontainers to boot the real database.\n- Whenever possible I've used Protocols as a static way of duck typing (more on that here: [Protocols](https://mypy.readthedocs.io/en/stable/protocols.html))\n\n## References\nI recommend these great resources about design patterns \n- Design Patterns: Elements of Reusable Object-Oriented Software\n- https://refactoring.guru/\n- [Christopher Okhravi's YT Channel](https://www.youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaikotek%2Fpython-design-patterns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsaikotek%2Fpython-design-patterns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsaikotek%2Fpython-design-patterns/lists"}