Python Adapter Pattern
The Adapter pattern is a structural design pattern that allows incompatible interfaces to collaborate. Just as a real-world power adapter lets plugs from different countries connect to a local socket, in programming the Adapter pattern acts as a bridge between two incompatible interfaces.
Core Concepts
The Adapter pattern mainly solves the problem of interface mismatch. When we need to use an existing class whose interface does not meet our needs, the Adapter pattern comes in handy. It converts the interface by creating an intermediate layer (the adapter), so that originally incompatible classes can work together.
Pattern Structure
The Adapter pattern contains three main roles:
- Target interface (Target): the interface the client expects
- Adapter: implements the target interface and wraps the adaptee
- Adaptee (Adaptee): the existing class that needs to be adapted
Why the Adapter Pattern Is Needed
Real-world Problem Scenario
Imagine you have an existing logging system that records logs using a specific method:
Example
class
LegacyLogger:
def
write_log
(
self
,
message
)
:
(
f
"[LEGACY] {message}"
)
But now you want to use a new logging interface:
Example
class
NewLogger:
def
log
(
self
,
level
,
message
)
:
(
f
"[{level.upper()}] {message}"
)
Without an adapter, you would have to modify all the code that calls the old logging system, which is both time-consuming and error-prone.
Advantages of the Adapter
- Code Reuse: existing classes can be reused without modifying source code
- Decoupling: separates interface conversion logic from business logic
- Flexibility: different implementations can be switched easily
- Follows the Open/Closed Principle: open for extension, closed for modification
Ways to Implement the Adapter Pattern
Class Adapter (using inheritance)
The class adapter implements interface adaptation through multiple inheritance:
Example
class
LegacyLogger:
"""The old logging class being adapted"""
def
write_log
(
self
,
message
)
:
(
f
"[LEGACY] {message}"
)
class
NewLoggerInterface:
"""Target interface"""
def
log
(
self
,
level
,
message
)
:
pass
class
LoggerAdapter
(
NewLoggerInterface
,
LegacyLogger
)
:
"""Class adapter - implemented via inheritance"""
def
log
(
self
,
level
,
message
)
:
Convert the new interface to the old interface
formatted_message
=
f
"{level}: {message}"
self
.
write_log
(
formatted_message
)
Usage examples
logger
=
LoggerAdapter
(
)
logger.
log
(
"INFO"
,
"System started successfully"
)
logger.
log
(
"ERROR"
,
"Database connection failed"
)
Output result:
[LEGACY] INFO: 系统启动成功
[LEGACY] ERROR: 数据库连接失败
Object Adapter (using composition)
The object adapter is implemented via composition, which is the more common approach:
Example
class
LegacyPayment:
"""The old payment system being adapted"""
def
process_payment
(
self
,
amount_in_dollars
)
:
(
f
"Processing payment: ${amount_in_dollars}"
)
return
True
class
NewPaymentInterface:
"""The new payment interface"""
def
pay
(
self
,
amount
,
currency
=
"CNY"
)
:
pass
class
PaymentAdapter
(
NewPaymentInterface
)
:
"""Object adapter - implemented via composition"""
def
init
(
self
,
legacy_payment
)
:
self
.
legacy_payment
=
legacy_payment
def
pay
(
self
,
amount
,
currency
=
"CNY"
)
:
Currency conversion logic
if
currency
==
"CNY"
:
amount_in_dollars
=
amount /
7.0
Simplified exchange rate conversion
else
:
amount_in_dollars
=
amount
Call the old system's interface
return
self
.
legacy_payment
.
process_payment
(
amount_in_dollars
)
Usage examples
legacy_payment
=
LegacyPayment
(
)
payment
=
PaymentAdapter
(
legacy_payment
)
Use the new interface to call the old system
payment.
pay
(
700
,
"CNY"
)
Pay 700 RMB
payment.
pay
(
100
,
"USD"
)
Pay 100 dollars
Output result:
处理支付: $100.0
处理支付: $100
Practical application cases
Case 1: Data Format Adapter
Example
import
json
class
XMLData:
"""XML data source"""
def
get_xml_data
(
self
)
:
return
"""
"""
class
JSONProcessor:
"""JSON processor (expects JSON format)"""
def
process_json
(
self
,
json_data
)
:
data
=
json.
loads
(
json_data
)
for
user
in
data
[
'users'
]
:
(
f
"Name: {user['name']}, Age: {user['age']}"
)
class
XMLToJSONAdapter:
"""XML to JSON adapter"""
def
init
(
self
,
xml_data
)
:
self
.
xml_data
=
xml_data
def
convert_to_json
(
self
)
:
Simplified XML to JSON conversion
xml_content
=
self
.
xml_data
.
get_xml_data
(
)
In real applications you should use libraries such as xml.etree.ElementTree for parsing here
json_data
=
{
"users"
:
[
{
"name"
:
"Zhang San"
,
"age"
:
25
}
,
{
"name"
:
"Li Si"
,
"age"
:
30
}
]
}
return
json.
dumps
(
json_data
,
ensure_ascii
=
False
)
Use the adapter
xml_source
=
XMLData
(
)
adapter
=
XMLToJSONAdapter
(
xml_source
)
json_processor
=
JSONProcessor
(
)
json_data
=
adapter.
convert_to_json
(
)
json_processor.
process_json
(
json_data
)
Output result:
姓名: 张三, 年龄: 25
姓名: 李四, 年龄: 30
Case 2: Third-party Service Adapter
Example
class
WeChatPay:
"""WeChat Pay SDK"""
def
wechat_pay
(
self
,
amount
,
user_id
)
:
(
f
"WeChat Pay: user {user_id} paid {amount} yuan"
)
return
{
"status"
:
"success"
,
"transaction_id"
:
"wx_123456"
}
class
AliPay:
"""Alipay SDK"""
def
alipay
(
self
,
money
,
user_account
)
:
(
f
"Alipay: account {user_account} paid {money} yuan"
)
return
{
"code"
:
200
,
"trade_no"
:
"ali_789012"
}
class
UnifiedPaymentAdapter:
"""Unified payment adapter"""
def
init
(
self
,
payment_service
)
:
self
.
payment_service
=
payment_service
def
pay
(
self
,
amount
,
user_info
)
:
Unified payment interface
if
isinstance
(
self
.
payment_service
,
WeChatPay
)
:
return
self
.
payment_service
.
wechat_pay
(
amount
,
user_info
)
elif
isinstance
(
self
.
payment_service
,
AliPay
)
:
return
self
.
payment_service
.
alipay
(
amount
,
user_info
)
else
:
raise
ValueError
(
"Unsupported payment method"
)
Client code can call it uniformly
def
process_order
(
payment_adapter
,
amount
,
user_info
)
:
"""Process order payment"""
result
=
payment_adapter.
pay
(
amount
,
user_info
)
(
f
"Payment result: {result}"
)
return
result
Usage examples
wechat_pay
=
WeChatPay
(
)
ali_pay
=
AliPay
(
)
wechat_adapter
=
UnifiedPaymentAdapter
(
wechat_pay
)
ali_adapter
=
UnifiedPaymentAdapter
(
ali_pay
)
A unified way of calling
process_order
(
wechat_adapter
,
100
,
"user_001"
)
process_order
(
ali_adapter
,
200
,
"user_002"
)
Output result:
微信支付: 用户user_001支付100元
支付结果: {'status': 'success', 'transaction_id': 'wx_123456'}
支付宝: 账户user_002支付200元
支付结果: {'code': 200, 'trade_no': 'ali_789012'}
Best Practices for the Adapter Pattern
1. Choose the right implementation approach
| Implementation | Applicable scenarios | Advantages | Disadvantages |
|---|---|---|---|
| Class Adapter | When there are few adaptee classes and the target interface is simple | Simple to implement, with little code | Requires multiple inheritance, which may make the class hierarchy complex |
| Object Adapter | Most scenarios, especially when multiple classes need to be adapted | More flexible, following the composition-over-inheritance principle | Requires creating an adapter object |
2. Keep the adapter's single responsibility
Example
Good practice: single responsibility
class
DataFormatAdapter:
"""Only responsible for data format conversion"""
def
convert_format
(
self
,
data
)
:
pass
Bad practice: too many responsibilities
class
BadAdapter:
"""Handles format conversion, validation, caching, etc. at the same time"""
def
convert_format
(
self
,
data
)
:
pass
def
validate_data
(
self
,
data
)
:
pass
def
cache_data
(
self
,
data
)
:
pass
3. Use interface abstraction
Example
from
abc
import
ABC
,
abstractmethod
class
PaymentInterface
(
ABC
)
:
"""Payment interface abstraction"""
@
abstractmethod
def
pay
(
self
,
amount
,
user_info
)
:
pass
class
LoggerInterface
(
ABC
)
:
"""Logging interface abstraction"""
@
abstractmethod
def
log
(
self
,
level
,
message
)
:
pass
Common Problems and Solutions
Problem 1: Too many adapters increase complexity
Solution: use the Factory pattern to create adapters
Example
class
AdapterFactory:
"""Adapter factory"""
@
staticmethod
def
create_payment_adapter
(
service_type
)
:
if
service_type
==
"wechat"
:
return
UnifiedPaymentAdapter
(
WeChatPay
(
)
)
elif
service_type
==
"alipay"
:
return
UnifiedPaymentAdapter
(
AliPay
(
)
)
else
:
raise
ValueError
(
f
"Unsupported payment type: {service_type}"
)
Use a factory to create the adapter
wechat_adapter
=
AdapterFactory.
create_payment_adapter
(
"wechat"
)
ali_adapter
=
AdapterFactory.
create_payment_adapter
(
"alipay"
)
Problem 2: Performance considerations
Solution: implement lazy loading and caching
Example
class
CachingAdapter:
"""Adapter with caching"""
def
init
(
self
,
adaptee
)
:
self
.
adaptee
=
adaptee
self
._cache
=
{
}
def
process_data
(
self
,
key
)
:
if
key
not
in
self
._cache:
simulate a time-consuming operation
result
=
self
.
adaptee
.
expensive_operation
(
key
)
self
._cache
[
key
]
=
result
return
self
._cache
[
key
]
Practical Exercise
Exercise 1: Create a file format adapter
Please implement a file format adapter that converts CSV-formatted data to JSON format:
Example
class
CSVReader:
"""CSV file reader"""
def
read_csv
(
self
,
filepath
)
:
Simulate reading a CSV file
return
[
[
"name"
,
"age"
,
"city"
]
,
[
"Alice"
,
"25"
,
"Beijing"
]
,
[
"Bob"
,
"30"
,
"Shanghai"
]
]
class
JSONExporter:
"""JSON exporter"""
def
export_json
(
self
,
data
)
:
import
json
(
"Export JSON data:"
)
(
json.
dumps
(
data
,
indent
=
2
,
ensure_ascii
=
False
)
)
Please implement the CSVToJSONAdapter class here
Your code...
Test code
csv_reader
=
CSVReader
(
)
json_exporter
=
JSONExporter
(
)
Create the adapter and test it
adapter
=
CSVToJSONAdapter
(
csv_reader
)
json_data
=
adapter.
convert_to_json
(
)
json_exporter.
export_json
(
json_data
)
Exercise 2: Design Thinking
Consider the following scenarios; how would you use the Adapter pattern:
- Your application needs to support multiple databases (MySQL, PostgreSQL, SQLite), but each database has a different connection method
- You need to integrate multiple third-party APIs, but their authentication methods and return formats differ
- Your system needs to support multiple message queues (RabbitMQ, Kafka, Redis)
Please design an Adapter pattern solution for one of these scenarios.
Summary
The Adapter pattern is an effective tool for solving interface incompatibility. After studying this article, you should have mastered:
- The basic concepts and applicable scenarios of the Adapter pattern
- The implementation approaches of class adapters and object adapters
- Application techniques in real projects
- Best practices and considerations for the Adapter pattern
Remember, the core idea of the Adapter pattern is "conversion" rather than "modification"; it helps us integrate new functionality without changing existing code, and is an important design pattern when maintaining large systems.
In real development, using the Adapter pattern properly can make your code more flexible, maintainable, and easy to extend.