Skip to content

Design Patterns

Proxy

The proxy's own check adds O(1) extra work (a constant amount) before it optionally does whatever the real object costs.

The idea, in plain English

A proxy works like a security guard standing in front of an office. Anyone who wants in has to go through the guard first. The guard checks your badge before letting you through to the real office. In code, a proxy object stands in front of the real object and controls access to it. It might check permissions, cache results, or log calls first.

How it works

  1. 1You create a proxy object with the exact same method names as the real object.
  2. 2You have callers talk to the proxy, instead of the real object directly.
  3. 3The proxy does its own check first — permission, cache, or logging. It only forwards the call to the real object when it decides to.

When you'd use it

Use this when you need to control or add a step before reaching an object. Examples: permission checks, caching expensive results, loading something heavy only when needed, or logging every access.

Common beginner mistakes

  • Always forward the call to the real object when access should be allowed, or valid requests get nothing back.
  • Don't pack unrelated logic into the proxy. Keep it a simple gatekeeper, not its own tangled system.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Access denied: no badge
Entered the office

Not sure this is the right topic? See the learning paths → or where this leads →