Proxy Pattern
Some objects are expensive or sensitive to touch. A high-resolution scan takes seconds to load from disk. A document store lives on another server, so every call crosses the network. A payroll record should only be read by HR. You want the rest of the code to use these objects normally, but something has to decide when and whether the real work happens.
The Proxy pattern puts a stand-in in front of the real object. The stand-in has exactly the same interface, so callers can't tell the difference. Inside, it decides what to do before passing the call on: load the real object only on first use, check the caller's permissions, or answer from a cache.
🛡️ In one sentence: give clients an object with the same interface as the real one, which holds a reference to the real one and controls access to it (lazily creating it, checking permissions or caching its answers).
The Problem It Solves
Here is a document service for an internal wiki. The store is remote and slow, and some documents are restricted. Without a proxy, those concerns end up in every caller.
class RemoteDocumentStore:
def fetch(self, doc_id: str) -> Document:
return self._http_get(f"/docs/{doc_id}") # ~200 ms over the network
class WikiPage:
def __init__(self, store: RemoteDocumentStore, cache: dict[str, Document]) -> None:
self.store = store
self.cache = cache
def render(self, user: User, doc_id: str) -> str:
if doc_id in RESTRICTED and "hr" not in user.roles:
raise PermissionError(doc_id)
if doc_id not in self.cache:
self.cache[doc_id] = self.store.fetch(doc_id)
return self.cache[doc_id].to_html()
That is fine for one caller. But the wiki also has a search page, a PDF export and a daily digest email, and each of them fetches documents.
The rules are copied into every caller. Each one repeats the permission check and the cache lookup. When the rule changes ("managers can also read HR documents"), you have to find and edit every copy.
One forgotten copy is a security hole. The PDF export was written in a hurry and calls store.fetch directly.
It works, every test passes, and it hands restricted documents to anyone who asks for an export.
The caller does three jobs. WikiPage should turn a document into HTML. Now it also knows about roles, cache
invalidation and network latency. It can't be tested without building all of that.
You can't change the policy in one place. Turning the cache off for debugging, or adding an audit log of who read what, means editing every class that touches the store.
⚠️ The smell to look for: the same "before I call this object, check X / look in Y / create it if needed" code repeated at every call site of one object. That logic belongs in one object that stands in front of it.