Proxy (aka Surrogate)

Intent

  • Provide a surrogate or placeholder for another object to control access to it.

Problem

  • How can the access to an object be controlled?

  • How can additional functionality be provided when accessing an object?

Solution

  • Define a separate Proxy object that acts as substitute for another object (Subject).

  • Work through a Proxy object to control the access to a real subject.

Types of Proxy

  • Remote Proxy

  • Virtual Proxy

  • Protection Proxy

  • Caching Proxy

  • Smart Proxy

Advantages

✅ You can control the service object without clients knowing about it. ✅ You can manage the lifecycle of the service object when clients don’t care about it. ✅ The proxy works even if the service object isn’t ready or is not available. ✅ Open/Closed Principle. You can introduce new proxies without changing the service or clients.

Disadvantages

❌ The code may become more complicated since you need to introduce a lot of new classes. ❌ The response from the service might get delayed.

Notes

  • Proxy pattern is also known as Surrogate pattern.

  • Some common operations done through proxy pattern includes,

    • May hide information about the real object to the client.

    • May perform optimization like on demand loading.

    • May do additional house-keeping job like audit tasks.

Last updated