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:
- Improve code reusability: avoid reinventing the wheel
- Enhance code maintainability: make the code structure clearer
- Promote team collaboration: provide a unified language and way of thinking
- Improve code quality: proven solutions are more reliable
An analogy of design patterns in daily life
Imagine you want to build a house:
- The primitive way: designing from scratch every time, error-prone and inefficient
- Using design patterns: using standard architectural blueprints, knowing the standard layouts of living rooms, kitchens, and bedrooms
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. |
|
- Adapter pattern (Adapter Pattern)
- Bridge pattern (Bridge Pattern)
- Filter / Criteria pattern (Filter / Criteria Pattern)
- Composite pattern (Composite Pattern)
- Decorator pattern (Decorator Pattern)
- Facade pattern (Facade Pattern)
- Flyweight pattern (Flyweight Pattern)
- Proxy pattern (Proxy Pattern)
- Chain of Responsibility pattern (Chain of Responsibility Pattern)
- Command pattern (Command Pattern)
- Interpreter pattern (Interpreter Pattern)
- Iterator pattern (Iterator Pattern)
- Mediator pattern (Mediator Pattern)
- Memento pattern (Memento Pattern)
- Observer pattern (Observer Pattern)
- State pattern (State Pattern)
- Null Object pattern (Null Object Pattern)
- Strategy pattern (Strategy Pattern)
- Template Method pattern (Template Method Pattern)
- Visitor pattern (Visitor Pattern)
- MVC pattern (Model-View-Controller Pattern)
- Business Delegate pattern (Business Delegate Pattern)
- Composite Entity pattern (Composite Entity Pattern)
- Data Access Object pattern (Data Access Object Pattern)
- Front Controller pattern (Front Controller Pattern)
- Intercepting Filter pattern (Intercepting Filter Pattern)
- Service Locator pattern (Service Locator Pattern)
- Transfer Object pattern (Transfer Object Pattern)
The following image shows the relationships and hierarchy among the various design pattern categories:

Advantages of design patterns
- Provides a unified design language, enabling developers to quickly communicate design intent.
- Provides mature, reusable solutions to common problems.
- Reduces system coupling and improves code maintainability and extensibility.
- Reduces repetitive design and improves development efficiency and code quality.
- Helps new members quickly understand the system architecture and design ideas.
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
)
(
"Creating a new database connection"
)
return
cls._instance
def
connect
(
self
)
:
(
"Connecting to the database"
)
Usage examples
db1
=
DatabaseConnection
(
)
db2
=
DatabaseConnection
(
)
(
f
"Are db1 and db2 the same instance? {db1 is db2}"
)
Output: True
Application scenarios:
- Database connection pool
- Configuration manager
- Logger
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
)
:
(
f
"Sending email: {message}"
)
class
SMSNotification
(
Notification
)
:
def
send
(
self
,
message:
str
)
:
(
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
=
NotificationFactory.
create_notification
(
"email"
)
sms
=
NotificationFactory.
create_notification
(
"sms"
)
.
send
(
"Your order has been shipped"
)
sms.
send
(
"Verification code: 123456"
)
Code Explanation:
Notificationis an abstract base class that defines the interfaceEmailNotificationandSMSNotificationis a concrete implementationNotificationFactoryresponsible for creating concrete notification objects
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
)
:
(
f
"{self.name} received email notification: {message}"
)
class
SMSSubscriber
(
Observer
)
:
def
init
(
self
,
name:
str
)
:
self
.
name
=
name
def
update
(
self
,
message:
str
)
:
(
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
(
)
(
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"
)