In this lesson, you will learn how to use the Proxy pattern to act as a gatekeeper for expensive objects, deferring their creation and monitoring their usage.
The Core Concept
Sometimes, an object represents a resource that is "heavy"—perhaps a database connection or a massive file that takes seconds to initialize. You don’t want to load this resource if it isn't strictly necessary. A Proxy is an object that mirrors the interface of the real object but intercepts requests to it. It acts as a lightweight placeholder, only "waking up" the actual object the moment it is needed, a technique known as lazy loading.
Implementing a Virtual Proxy
Imagine we have a HeavyReport class that consumes significant memory upon instantiation. Instead of using it directly, we create a ReportProxy that holds a reference to the real object but keeps it None until a method is called.
class HeavyReport:
def __init__(self):
print("Expensive initialization: Loading millions of records...")
self.data = "Processed Data"
def get_data(self):
return self.data
class ReportProxy:
def __init__(self):
self._real_report = None
def get_data(self):
# Lazy Loading: The real object is only created on demand
if self._real_report is None:
print("Proxy: Initializing the real report now.")
self._real_report = HeavyReport()
# Transparent Logging: We can track access to the resource
print("Proxy: Logging access to data.")
return self._real_report.get_data()
# Usage
proxy = ReportProxy()
print("Proxy created, but no heavy work done yet.")
print(proxy.get_data())
Why Use This?
- Efficiency: By employing lazy loading, you avoid unnecessary memory overhead if the application logic branches away from using the heavy resource.
- Access Control: Because the proxy intercepts calls, you can easily add security checks, logging, or caching without changing the code of the underlying
HeavyReportclass. - Transparency: To the client, the
ReportProxybehaves exactly like theHeavyReport. The complexity of the initialization is hidden behind the interface.
Key Takeaway: The Proxy pattern allows you to substitute a resource-heavy object with a lightweight surrogate that manages access, logs interactions, and ensures the real object is only initialized when absolutely required.