Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 57 ยท Structural Patterns

Proxy

Learn the Proxy design pattern: virtual, protection, caching and logging proxies, the JavaScript Proxy object, and how a remote proxy hides the network.

The Proxy pattern places a stand-in object in front of another object (the real subject) and gives the stand-in the same interface. Clients use the proxy as if it were the real thing, and the proxy decides whether, when and how to forward each call. That control point is the whole value: the proxy can delay creating an expensive object, check permissions, remember results, log calls or hide the fact that the real object lives on another machine.

A proxy and a Decorator look alike in a class diagram, because both wrap an object of the same type. The difference is intent. A decorator adds responsibilities and the client usually builds the stack. A proxy controls access to the subject, and often creates or manages the subject itself, so the client may not even know a real subject exists.

Common kinds of proxy

Virtual Creates the costly object only when first needed.
Protection Checks who may call what.
Caching Remembers results of slow calls.
Logging Records every call and result.

The interface is the same; the control logic is what differs.

1 / 3

The structure

classDiagram
    class Subject {
        <<interface>>
        +request()
    }
    class RealSubject {
        +request()
    }
    class Proxy {
        -real
        +request()
    }
    class Client
    Subject <|.. RealSubject
    Subject <|.. Proxy
    Proxy --> RealSubject : controls access
    Client --> Subject

The client depends only on the Subject interface, so it cannot tell whether it talks to the proxy or the real object.

A virtual proxy: create it when needed

Some objects are expensive to build: they load a big file, open a connection or decode an image. A virtual proxy defers that cost until the first call that really needs it. If nobody ever uses the object, the cost is never paid.

JS A lazy image that loads on first draw

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Protection, caching and logging

These three share a shape: wrap the call, do a small extra step, forward. Here they guard, remember and record the same service. They are written as classes so that each one is a real proxy with the same getReport(id) interface.

JS Protection, caching and logging proxies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second manager call prints nothing from the service, because the caching proxy answered it. The intern never reaches the cache or the service, because the protection proxy refused first. Because every layer has the same interface, you can reorder or remove layers without touching the client.

The JavaScript Proxy object

JavaScript has the pattern built into the language. new Proxy(target, handler) creates an object that intercepts operations such as reading a property (get), writing one (set), checking in (has), deleting (deleteProperty) or calling a function (apply). You do not need to write a wrapper class for every interface: one handler works for any target.

JS The built-in Proxy: validation and logging

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reflect.get forwards the operation with its default behavior, which keeps getters and the correct this working. Frameworks use this mechanism: Vue 3's reactivity system wraps your state in a Proxy so it notices reads and writes. Be aware that a proxy is a different object from its target, so proxy === target is false, and a few built-ins with internal slots (such as Map) need extra care when proxied.

Remote proxy

A remote proxy (also called an ambassador) represents an object that lives in another process or on another machine. It has the same interface as the remote object, and each method serializes its arguments, sends them over the network, waits for the answer and deserializes it. The caller writes account.getBalance() and the network is hidden. Java RMI, gRPC stubs and generated REST clients work this way. The site cannot open real network connections from this page, so here is the shape as a read-only snippet and a runnable stand-in below it.

Java
// Read-only: the shape of a remote proxy (stub) in Java-like code.
interface Account {
    long getBalance(String id);
}

class AccountStub implements Account {
    private final RemoteChannel channel;     // knows the host and protocol

    AccountStub(RemoteChannel channel) { this.channel = channel; }

    public long getBalance(String id) {
        String reply = channel.call("getBalance", id);   // serialize, send, wait
        return Long.parseLong(reply);                    // deserialize
    }
}
JS A remote proxy with a fake network

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real here: the shape of the idea, including JSON messages and a stub that looks like a local object. What is the stand-in: there is no socket, timeout, retry or failure; a real remote proxy must handle all of those, and callers should remember that a remote call can fail in ways a local call cannot.

Choosing and avoiding

  • If the new behavior is an optional enhancement chosen by the client, prefer a Decorator. If it is control over access to a particular object, use a proxy.
  • A proxy differs from an Adapter, which gives the subject a different interface.
  • Every proxy adds a hop. Measure before adding a caching proxy, and think about when cached data becomes stale.
  • Avoid proxies that change meaning. A protection proxy that quietly returns empty data instead of failing makes bugs hard to find.
  • A lazy proxy shifts a cost to an unpredictable moment. That is a feature for startup time and a surprise for latency-sensitive code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the defining feature of the Proxy pattern?

    A proxy shares the real subject's interface and sits in front of it, deciding whether and how calls get through.
  2. 2. Which proxy creates an expensive object only when it is first used?

    A virtual proxy defers creation until a call needs the real object, which saves the cost if it is never used.
  3. 3. In the JavaScript Proxy example, what does the set trap allow you to do?

    Traps such as get, set and apply intercept operations on the target, so one handler can add validation or logging for any object.
  4. 4. How does a Proxy differ from a Decorator in intent?

    Both wrap an object with the same interface, but the proxy decides if and when the subject is reached, while the decorator extends what the subject does.
  5. 5. Why should callers remember that a remote proxy hides a network call?

    The proxy hides location, not the laws of networks. Latency, partial failure and retries still have to be designed for.

Summary

  • A proxy has the same interface as its subject and controls access to it.
  • Virtual proxies delay expensive creation; protection proxies check permissions; caching proxies reuse results; logging proxies record calls.
  • JavaScript's Proxy and Reflect give you the pattern with traps such as get, set and apply.
  • A remote proxy hides serialization and transport, but not the possibility of failure.
  • Proxy controls access; Decorator adds behavior; Adapter changes the interface.

Next lesson: Strategy.