Python Proxy Pattern
The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. Simply put, a proxy is an intermediary that acts between the client and the target object.
Real-Life Proxy Analogies
Imagine scenarios in real life:
- Real estate agent: You don't need to communicate directly with the homeowner; through the agent you can learn about listings and arrange viewings
- Celebrity agent: When a company wants to invite a celebrity for endorsement, it needs to negotiate cooperation details through the agent
- Web proxy server: Your network requests first pass through the proxy server, which then forwards them to the target website
In these examples, the intermediary/agent is the proxy, controlling access to the real object.
Core Components of the Proxy Pattern
The Proxy Pattern typically involves three key roles:
1. Abstract Subject (Subject)
Defines a common interface for the Real Subject and the Proxy, so that the Proxy can be used wherever the Real Subject is used.
2. Real Subject (Real Subject)
Defines the real object represented by the proxy; it is the object ultimately referenced.
3. Proxy (Proxy)
Holds a reference that lets the proxy access the entity, provides an interface identical to the Real Subject's, and controls access to the Real Subject.

Types of the Proxy Pattern
The Proxy Pattern has several variants, each with different application scenarios:
1. Virtual Proxy (Virtual Proxy)
Defers the creation of an expensive object until it is actually needed.
2. Protection Proxy (Protection Proxy)
Controls access to the original object; used when the object should have different access permissions.
3. Remote Proxy (Remote Proxy)
Provides a local representative for an object located in a different address space.
4. Smart Reference Proxy (Smart Reference Proxy)
Performs additional operations when accessing the object, such as reference counting and lazy loading.
Implementing the Proxy Pattern in Python
Let's understand the implementation of the Proxy Pattern through concrete code examples.
Basic Interface Definition
First, we define the abstract subject interface:
Example
from
abc
import
ABC
,
abstractmethod
from
typing
import
Any
class
Subject
(
ABC
)
:
"""
Abstract subject interface defining the common operations of the Real Subject and the Proxy
"""
@
abstractmethod
def
request
(
self
)
Any:
"""The main method for executing the request"""
pass
Real Subject Implementation
Example
class
RealSubject
(
Subject
)
:
"""
The Real Subject class, containing the core business logic
Usually expensive to create and initialize
"""
def
init
(
self
,
name:
str
)
:
self
.
name
=
name
(
f
"Creating RealSubject instance: {self.name} (this is an expensive operation)"
)
def
request
(
self
)
str
:
"""Execute the real request"""
(
f
"RealSubject: handling request - {self.name}"
)
return
f
"Response from {self.name}"
Proxy Class Implementation
Example
class
Proxy
(
Subject
)
:
"""
The Proxy class, controlling access to the Real Subject
Can add extra functionality such as lazy loading and access control
"""
def
init
(
self
,
subject_name:
str
)
:
self
.
subject_name
=
subject_name
self
._real_subject
=
None
Lazy initialization
def
_lazy_init
(
self
)
None
:
"""Lazily load the Real Subject object"""
if
self
._real_subject
is
None
:
self
._real_subject
=
RealSubject
(
self
.
subject_name
)
def
request
(
self
)
str
:
"""The proxy's request method, which can add extra logic"""
(
"Proxy: preprocessing before calling the real object"
)
Lazily load the real object
self
._lazy_init
(
)
Call the real object's method
result
=
self
._real_subject.
request
(
)
(
"Proxy: post-processing after calling the real object"
)
return
f
"Proxy-enhanced result: {result}"
Client code
Example
def
client_code
(
subject: Subject
)
None
:
"""
Client code that interacts with the subject through the abstract interface
Neither knows nor cares whether it is using the Real Subject or the Proxy
"""
(
"Client: starting operation"
)
result
=
subject.
request
(
)
(
f
"Client: received result - {result}"
)
(
)
Usage examples
if
name
==
"main"
:
(
"Using the Real Subject directly:"
)
real_subject
=
RealSubject
(
"Real Object A"
)
client_code
(
real_subject
)
(
"Using the Proxy:"
)
proxy
=
Proxy
(
"Proxy Object B"
)
client_code
(
proxy
)
Use the same proxy again to observe the lazy-loading effect
(
"Using the same proxy again:"
)
client_code
(
proxy
)
Running the above code, you will see the following output:
直接使用真实主题:
创建 RealSubject 实例: 真实对象A (这是一个昂贵的操作)
客户端: 开始执行操作
RealSubject: 处理请求 - 真实对象A
客户端: 收到结果 - 来自 真实对象A 的响应
Use proxy:
客户端: 开始执行操作
Proxy: 在调用真实对象前进行预处理
创建 RealSubject 实例: 代理对象B (这是一个昂贵的操作)
RealSubject: 处理请求 - 代理对象B
Proxy: 在调用真实对象后进行后处理
客户端: 收到结果 - 代理增强的结果: 来自 代理对象B 的响应
Use the same proxy again:
客户端: 开始执行操作
Proxy: 在调用真实对象前进行预处理
RealSubject: 处理请求 - 代理对象B
Proxy: 在调用真实对象后进行后处理
客户端: 收到结果 - 代理增强的结果: 来自 代理对象B 的响应
Practical Example: Image Loading Proxy
Let's look at a more practical example - a virtual proxy for image loading.
Image Loading System
Example
from
pathlib
import
Path
import
time
class
Image:
"""Real image class, simulating the expensive operation of loading a large image"""
def
init
(
self
,
filename:
str
)
:
self
.
filename
=
filename
self
._load_image
(
)
def
_load_image
(
self
)
None
:
"""Simulate the expensive operation of loading a large image"""
(
f
"Loading image: {self.filename} (this may take a few seconds...)"
)
time
.
sleep
(
2
)
Simulate loading time
(
f
"Image {self.filename} loaded!"
)
def
display
(
self
)
None
:
"""Display the image"""
(
f
"Displaying image: {self.filename}"
)
class
ImageProxy:
"""Image proxy implementing lazy loading"""
def
init
(
self
,
filename:
str
)
:
self
.
filename
=
filename
self
._image
=
None
def
display
(
self
)
None
:
"""Display the image, loading it first if necessary"""
if
self
._image
is
None
:
(
"Proxy: detected that the image is not loaded, starting lazy loading..."
)
self
._image
=
Image
(
self
.
filename
)
else
:
(
"Proxy: image already loaded, displaying directly"
)
self
._image.
display
(
)
Usage examples
def
demo_image_proxy
(
)
:
(
"Creating image proxy (the image is not loaded immediately)"
)
proxy
=
ImageProxy
(
"large_photo.jpg"
)
(
"\nFirst call to display() - triggers lazy loading:"
)
proxy.
display
(
)
(
"\nSecond call to display() - directly uses the loaded image:"
)
proxy.
display
(
)
Running the Example
demo_image_proxy
(
)
Protection Proxy Example: Access Control
A protection proxy is used to control access to sensitive resources.
Example
class
SensitiveData:
"""Sensitive data class"""
def
init
(
self
,
data:
str
)
:
self
.
data
=
data
def
read_data
(
self
)
str
:
"""Read sensitive data"""
return
f
"Sensitive data: {self.data}"
class
ProtectionProxy:
"""Protection proxy implementing access control"""
def
init
(
self
,
sensitive_data: SensitiveData
,
user_role:
str
)
:
self
._sensitive_data
=
sensitive_data
self
.
user_role
=
user_role
def
read_data
(
self
)
str
:
"""Read data, but perform a permission check"""
if
self
.
user_role
!=
"admin"
:
return
"Error: insufficient permissions; only administrators can access sensitive data"
return
self
._sensitive_data.
read_data
(
)
Usage examples
def
demo_protection_proxy
(
)
:
sensitive_data
=
SensitiveData
(
"Confidential information: the project budget is 1 million yuan"
)
Regular user attempts access
user_proxy
=
ProtectionProxy
(
sensitive_data
,
"user"
)
(
"Regular user attempting access:"
)
(
user_proxy.
read_data
(
)
)
Administrator access
admin_proxy
=
ProtectionProxy
(
sensitive_data
,
"admin"
)
(
"\nAdministrator access:"
)
(
admin_proxy.
read_data
(
)
)
demo_protection_proxy
(
)
Advantages and Disadvantages of the Proxy Pattern
Advantages
- Controlled object access: The proxy can control how and when the client accesses the real object
- Lazy-loading optimization: A virtual proxy can delay the creation of expensive objects, improving performance
- Enhanced security: A protection proxy can add access-control logic
- Open-Closed Principle: New proxies can be introduced without modifying client code
- Separation of responsibilities: The proxy can handle auxiliary functions unrelated to core business logic
Disadvantages
- Increased complexity: Introduces a new abstraction layer, making the code structure more complex
- Response latency: The proxy may increase request processing time
- Possible over-engineering: For simple scenarios, using a proxy may be unnecessary
Application Scenarios of the Proxy Pattern
The Proxy Pattern is especially useful in the following scenarios:
1. Lazy Loading (Lazy Loading)
When an object is expensive to create but may not be used immediately.
2. Access Control (Access Control)
When access to certain objects needs to be restricted.
3. Remote Representation (Remote Representation)
Provides a local interface for a remote object, such as an RPC call.
4. Logging (Logging)
Add logging before and after method calls.
5. Caching (Caching)
Provide caching for the results of expensive operations.
Practical Exercise
To reinforce your understanding of the Proxy Pattern, try the following exercises:
Exercise 1: Caching Proxy
Create a caching proxy that adds caching to a function computing the Fibonacci sequence:
Example
class
FibonacciCalculator:
"""Compute the Fibonacci sequence"""
def
fibonacci
(
self
,
n:
int
)
int
:
if
n
<=
1
:
return
n
return
self
.
fibonacci
(
n -
1
)
self
.
fibonacci
(
n -
2
)
Your task: implement the FibonacciCacheProxy class
Requirement: add caching to Fibonacci computation to avoid repeated calculations
class
FibonacciCacheProxy:
def
init
(
self
)
:
self
._calculator
=
FibonacciCalculator
(
)
self
._cache
=
{
}
Implement the caching logic here
def
fibonacci
(
self
,
n:
int
)
int
:
Implement caching logic
pass
Test code
def
test_cache_proxy
(
)
:
proxy
=
FibonacciCacheProxy
(
)
(
"First computation of fib(10):"
)
result1
=
proxy.
fibonacci
(
10
)
(
f
"Result: {result1}"
)
(
"Second computation of fib(10) (should come from cache):"
)
result2
=
proxy.
fibonacci
(
10
)
(
f
"Result: {result2}"
)
(
f
"The two results are the same: {result1 == result2}"
)
Exercise 2: Logging Proxy
Create a logging proxy that records method call information:
Example
class
DatabaseService:
"""Database service"""
def
query
(
self
,
sql:
str
)
str
:
return
f
"Executing query: {sql}"
def
update
(
self
,
sql:
str
)
str
:
return
f
"Executing update: {sql}"
Your task: implement the LoggingProxy class
Requirement: record the call time, parameters, and result of each method
class
LoggingProxy:
def
init
(
self
)
:
self
._service
=
DatabaseService
(
)
def
query
(
self
,
sql:
str
)
str
:
Add logging logic
pass
def
update
(
self
,
sql:
str
)
str
:
Add logging logic
pass
Summary
The Proxy Pattern is a powerful design pattern that controls access to real objects by introducing an intermediate layer. Implementing it in Python is relatively simple, largely thanks to Python's dynamic features.
Key Points
- The proxy is an intermediary: Acts as a middleman between the client and the real object
- Consistent interface: The proxy and the real object implement the same interface
- Controlled access: The proxy can add extra control logic such as lazy loading and permission checks
- Flexible application: Choose different proxy types according to your needs