Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Design Patterns

Python Design Patterns

Design patterns are, for common problems in software development,reusable solutions. They are not complete designs that can be directly converted into code, but rather, for solving specific problems,templates or blueprints.

The core value of design patterns

Design patterns are like standard blueprints in architecture, providing the following benefits for software development:

An analogy of design patterns in daily life

Imagine you want to build a house:

Design patterns are the "standard architectural blueprints" of software development.

Types of design patterns

According to the classic book "Design Patterns - Elements of Reusable Object-Oriented Software" (Chinese translation: "Design Patterns: Elements of Reusable Object-Oriented Software") 's definition, there are 23 classic design patterns in total. Based on their focus, these patterns can be divided into three major categories: Creational Patterns, Structural Patterns, and Behavioral Patterns. In addition, in enterprise development there is another commonly used category of architectural-level design patterns.

No. Pattern & Description Includes
1 Creational Patterns
Used to solve object creation problems; by encapsulating instantiation logic and hiding concrete implementation details, it makes the system more flexible and extensible when creating objects.
  • Factory pattern (Factory Pattern)
  • Abstract factory pattern (Abstract Factory Pattern)
  • Singleton pattern (Singleton Pattern)
  • Builder pattern (Builder Pattern)
  • Prototype pattern (Prototype Pattern)
  • | | 2 | **Structural Patterns** focus on the composition and collaboration of classes and objects, helping us build flexible, reusable, and extensible system structures. | | | 3 | **Behavioral Patterns** focus on communication and responsibility assignment among objects, improving system flexibility and maintainability by encapsulating algorithms, states, or request logic. | | | 4 | **Enterprise-level architectural patterns** These patterns are often used in the layered architecture of large systems, focusing on the collaboration between the presentation layer and the business logic layer. | |

    The following image shows the relationships and hierarchy among the various design pattern categories:

    Relationships Between Design Patterns

    Advantages of design patterns

    The six principles of design patterns

    1. Open-closed principle (Open-Closed Principle)

    Open for extension, closed for modification. Software should adapt to change by extending new functionality rather than modifying existing code. The core of implementing this principle lies in using abstractions (interfaces or base classes) to define stable behavior.

    2. Liskov substitution principle (Liskov Substitution Principle)

    Wherever a base class appears, a subclass should be able to substitute for it. Inheritance only makes sense when derived classes can fully replace the base class. This principle guarantees the correctness of polymorphism and is an important complement to the Open-Closed Principle.

    3. Dependency inversion principle (Dependency Inversion Principle)

    High-level modules should not depend on low-level modules; both should depend on abstractions. Concrete implementations should depend on interfaces or abstract classes rather than directly on concrete classes. This principle makes the system easier to extend and test.

    4. Interface segregation principle (Interface Segregation Principle)

    A class should not depend on interfaces it does not need. Large interfaces should be split into multiple smaller, more specialized ones to reduce coupling and increase flexibility.

    5. Law of Demeter (Law of Demeter)

    Also known as the "Least Knowledge Principle": an object should minimize its interactions with other objects. In other words, a class should only know about objects directly related to itself, thereby reducing system complexity.

    6. Composite reuse principle (Composite Reuse Principle)

    Prefer composition or aggregation over inheritance to achieve reuse. Inheritance creates strong coupling, whereas composition allows dependencies to be flexibly replaced at runtime, enabling a more elegant structural design.


    Common design pattern examples in Python

    Let us understand the application of design patterns in Python through a few concrete examples.

    Singleton pattern (Singleton)

    The Singleton pattern ensures a class has only one instance and provides a global access point.

    Example

    class

    DatabaseConnection:

        _instance

    =

    None

       

       

    def

    new

    (

    cls

    )

    :

           

    if

    cls._instance

    is

    None

    :

                cls._instance

    =

    super

    (

    )

    .

    new

    (

    cls

    )

               

    print

    (

    "Creating a new database connection"

    )

           

    return

    cls._instance

       

       

    def

    connect

    (

    self

    )

    :

           

    print

    (

    "Connecting to the database"

    )

    Usage examples

    db1

    =

    DatabaseConnection

    (

    )

    db2

    =

    DatabaseConnection

    (

    )

    print

    (

    f

    "Are db1 and db2 the same instance? {db1 is db2}"

    )

     

    Output: True

    Application scenarios:

    Factory pattern (Factory)

    The Factory pattern provides an interface for creating objects, letting subclasses decide which class to instantiate.

    Example

    from

    abc

    import

    ABC

    ,

    abstractmethod

    Abstract product

    class

    Notification

    (

    ABC

    )

    :

       

    @

    abstractmethod

       

    def

    send

    (

    self

    ,

    message:

    str

    )

    :

           

    pass

    Concrete product

    class

    EmailNotification

    (

    Notification

    )

    :

       

    def

    send

    (

    self

    ,

    message:

    str

    )

    :

           

    print

    (

    f

    "Sending email: {message}"

    )

    class

    SMSNotification

    (

    Notification

    )

    :

       

    def

    send

    (

    self

    ,

    message:

    str

    )

    :

           

    print

    (

    f

    "Sending SMS: {message}"

    )

    Factory class

    class

    NotificationFactory:

       

    @

    staticmethod

       

    def

    create_notification

    (

    notification_type:

    str

    )

    Notification:

           

    if

    notification_type

    ==

    "email"

    :

               

    return

    EmailNotification

    (

    )

           

    elif

    notification_type

    ==

    "sms"

    :

               

    return

    SMSNotification

    (

    )

           

    else

    :

               

    raise

    ValueError

    (

    "Unsupported notification type"

    )

    Usage examples

    email

    =

    NotificationFactory.

    create_notification

    (

    "email"

    )

    sms

    =

    NotificationFactory.

    create_notification

    (

    "sms"

    )

    email

    .

    send

    (

    "Your order has been shipped"

    )

    sms.

    send

    (

    "Verification code: 123456"

    )

    Code Explanation:

    Observer pattern (Observer)

    The Observer pattern defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified.

    Example

    from

    abc

    import

    ABC

    ,

    abstractmethod

    Observer interface

    class

    Observer

    (

    ABC

    )

    :

       

    @

    abstractmethod

       

    def

    update

    (

    self

    ,

    message:

    str

    )

    :

           

    pass

    Concrete observer

    class

    EmailSubscriber

    (

    Observer

    )

    :

       

    def

    init

    (

    self

    ,

    name:

    str

    )

    :

           

    self

    .

    name

    =

    name

       

       

    def

    update

    (

    self

    ,

    message:

    str

    )

    :

           

    print

    (

    f

    "{self.name} received email notification: {message}"

    )

    class

    SMSSubscriber

    (

    Observer

    )

    :

       

    def

    init

    (

    self

    ,

    name:

    str

    )

    :

           

    self

    .

    name

    =

    name

       

       

    def

    update

    (

    self

    ,

    message:

    str

    )

    :

           

    print

    (

    f

    "{self.name} received SMS notification: {message}"

    )

    Subject (the observed)

    class

    NewsPublisher:

       

    def

    init

    (

    self

    )

    :

           

    self

    ._subscribers

    =

    [

    ]

       

       

    def

    subscribe

    (

    self

    ,

    subscriber: Observer

    )

    :

           

    self

    ._subscribers.

    append

    (

    subscriber

    )

       

       

    def

    unsubscribe

    (

    self

    ,

    subscriber: Observer

    )

    :

           

    self

    ._subscribers.

    remove

    (

    subscriber

    )

       

       

    def

    notify_subscribers

    (

    self

    ,

    message:

    str

    )

    :

           

    for

    subscriber

    in

    self

    ._subscribers:

                subscriber.

    update

    (

    message

    )

    Usage examples

    publisher

    =

    NewsPublisher

    (

    )

    Create subscribers

    alice

    =

    EmailSubscriber

    (

    "Alice"

    )

    bob

    =

    SMSSubscriber

    (

    "Bob"

    )

    Subscribe to news

    publisher.

    subscribe

    (

    alice

    )

    publisher.

    subscribe

    (

    bob

    )

    Publish news

    publisher.

    notify_subscribers

    (

    "Python 3.12 has been released!"

    )

    Cancel the subscription

    publisher.

    unsubscribe

    (

    alice

    )

    publisher.

    notify_subscribers

    (

    "This is a notification only Bob can see"

    )


    Special considerations for design patterns in Python

    Python's dynamic features

    As a dynamic language, Python makes some design patterns simpler to implement:

    Example

    Python-style simple factory

    def

    create_payment

    (

    method

    )

    :

        payment_methods

    =

    {

           

    'credit_card'

    : CreditCardPayment

    ,

           

    'paypal'

    : PayPalPayment

    ,

           

    'alipay'

    : AlipayPayment

       

    }

       

    return

    payment_methods

    [

    method

    ]

    (

    )

    Use it directly, no complex class hierarchy needed

    payment

    =

    create_payment

    (

    'alipay'

    )

    Built-in support for the Decorator pattern

    Python has built-in decorator syntax, making the Decorator pattern more elegant to implement:

    Example

    def

    log_execution_time

    (

    func

    )

    :

       

    def

    wrapper

    (

    *args

    ,

    **kwargs

    )

    :

           

    import

    time

            start

    =

    time

    .

    time

    (

    )

            result

    =

    func

    (

    *args

    ,

    **kwargs

    )

            end

    =

    time

    .

    time

    (

    )

           

    print

    (

    f

    "{func.name} execution time: {end - start:.2f} seconds"

    )

           

    return

    result

       

    return

    wrapper

    @

    log_execution_time

    def

    process_data

    (

    data

    )

    :

       

    Simulate data processing

       

    import

    time

       

    time

    .

    sleep

    (

    1

    )

       

    return

    f

    "Processed data: {data}"

    Use

    result

    =

    process_data

    (

    "Sample data"

    )