Codacoda
Back to Academy

design patterns

Proxy

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the real object, so the client uses it transparently. The key participants are the Subject (defines the common interface for RealSubject and Proxy), RealSubject (the real object the proxy represents), and Proxy (maintains a reference to the RealSubject, controls access to it, and may handle creation or deletion). Common variants include Virtual Proxy (lazy initialization), Protection Proxy (access control), Remote Proxy (network resource access), and Caching Proxy (caches results). Think of a credit card as a proxy for a bank account: it provides the same 'pay' interface but controls access and adds validation. Use Proxy when you need a more versatile or sophisticated reference to an object than a simple pointer.

Use Cases

  • Lazy loading of expensive resources (images, large data)
  • Access control and permission checking
  • Logging and auditing method calls transparently
  • Caching results of expensive operations

Visualization

delegates<<interface>>Subject+request()RealSubject+request()Proxy+request()-realSubjectClient
Speed:1x
Proxy — provides a surrogate or placeholder for another object to control accessStep 1 / 8

Implementation

Output

Click "Run Code" to see output...