Proxy Pattern

Stand an object with the same interface in front of the real one so you can delay, deny, cache or log access without the caller knowing.

Overview

The problem it solves Sometimes you do not want a caller to reach an object directly. The object is expensive to create and may never be used. Or only some callers may touch it. Or it lives on another machine. Or its answers are worth remembering. A proxy is an object with the same interface as the real one. The caller talks to the proxy, and the proxy decides whether, when and how to reach the real object.

The pattern is a structural pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). Its roles are Subject (the shared interface), RealSubject (the object doing the work) and Proxy (the stand-in that controls access and usually holds or creates the real subject).

In the diagram below, the Subject is an image with a render() method, the RealSubject is RealImage, which holds the decoded pixels, and the Proxy is ImageProxy, which holds only the path until someone asks for a render.

Interview questions

  • What kinds of proxy are there, and how do you pick one?
  • How is Proxy different from Decorator when the code looks the same?
  • How do Java dynamic proxies and Spring AOP proxies work?
  • Write a generic proxy in Python without repeating every method.
  • What goes wrong with proxies in practice?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio