ConceptDifficulty: Intermediate1 min

Proxy Pattern Structure: The Class and Sequence Diagrams

Subject, RealSubject and Proxy share one interface; the sequence shows when the real object is created.

Proxy has four participants: the subject interface, the real subject that does the work, the proxy that stands in front of it, and the client. This card reads their roles off the Gang of Four's class diagram, then follows a virtual proxy through two requests to show when the real subject comes into being.

Proxy participants
Each participant and its role
ParticipantRole
SubjectThe interface the client uses, implemented by both the real subject and the proxy.
RealSubjectThe object that does the work, and knows nothing of the proxy.
ProxyImplements Subject, holds or creates the real subject, and decides whether and when to forward each call.
ClientHolds a Subject, and cannot tell whether it is the proxy or the real thing.

The class diagram looks like Decorator's, and the difference is in the intent and in one detail: a decorator is handed the object it wraps, while a proxy often creates or locates its real subject itself. The sequence diagram shows a virtual proxy doing exactly that.

A virtual proxy across two requests

The first request creates the real subject and then forwards to it. The second finds it already there and forwards straight away. Until the first request, the program has paid nothing for the real subject, and saving that cost is the reason for a virtual proxy.