Proxy Pattern

The Proxy pattern: a stand-in with the same interface as a real object that controls when and whether calls reach it, and the self-call it never sees.

  • 9 cards
  • 4 questions
  • About 17 min
  • Intermediate to Advanced
Share

Some objects should not be reached directly: one is expensive to create and may never be used, one holds data only some users may change, one lives on another machine, and one answers the same slow question again and again. The Proxy pattern puts a stand-in in front of the object, with the same interface, so the caller is unchanged while the stand-in decides whether, when and how each call reaches the real thing.

This topic opens on that need and the four kinds of proxy, virtual, protection, remote and caching, then reads the participants off the class diagram and follows a virtual proxy through a sequence diagram. The template creates the real object on its first use in Python, Java and TypeScript.

Two examples follow: a protection proxy that lets an editor delete a document and refuses a viewer, and JavaScript's built-in Proxy object, which intercepts reads and writes on any object. A comparison shows Python's __getattr__ forwarding every call in one method, and what it fails to forward. The gotcha is the call a real object makes to itself, which never passes through its proxy, and the exercise writes a caching proxy for exchange rates.

By the end you can recognise a proxy, name its kind, and predict which calls it does and does not see.

Contents

9 cardsnot started