Proxy

Provide a surrogate or placeholder for another object to control access to it. Use it when a remote proxy represents an object in a different address space, a virtual proxy creates expensive objects on demand, a protection proxy controls access rights, or a smart reference performs additional actions when an object is accessed.

Examples:

  • A credit card is a proxy for a bank account, which is itself a proxy for cash — all implement the same 'make a payment' interface, but the proxy adds safety and convenience without the consumer carrying loads of cash. In code, a lazy-loading proxy creates the real database object only on the first genuine request, returning cached results for subsequent calls.
// Virtual proxy defers creation of the real Image
class ImageProxy : public Graphic {
public:
  ImageProxy(const char* filename) : _filename(filename), _image(0) {}
  void Draw(const Point& at) override {
    GetImage()->Draw(at);
  }
  Point GetExtent() override {
    if (_image == 0) return _extent;  // return cached extent
    return _image->GetExtent();
  }
private:
  Image* GetImage() {
    if (_image == 0) _image = new Image(_filename);
    return _image;
  }
  const char* _filename;
  Image* _image;
  Point _extent;
};

Synonyms: surrogate