Proxy Pattern

Also known as : Surrogate

Proxy pattern suggests using a separate object referred to as a proxy instead of accessing the actual object. A Proxy exists because:

  • Creation of object may be expensive so its creation can be postponed till the very need arises and till then, a proxy can represent the target.
  • The location of the target object is not known or varies.
  • The target object might not be available or accessible.

Proxy features are

  • The Proxy object offers the same interface as the target object.
  • A link between SubjectProxy and RealSubject forwarding the requests from proxy to the real object; In my opinion this link should be optional.

Proxy and other patterns

Proxy can be compared to Facade, Decorator, Adapter and Chain of Responsibility but it is very different from them:

  • Clients usually can not interact with the target object directly, unlike Facade and Decorator.
  • Proxy differs from Decorator since Decorator adds functionality and does not control access to the target object.
  • Unlike Facade, the Proxy interacts with only one object.
  • As opposed to proxy, an adapter provides a different interface to the object it adapts. However, a proxy used for access protection might refuse to perform an operation that the subject will perform, so its interface may be effectively a subset of the subject's.

Different Proxies

We have different types of proxies: Remote Proxy, Virtual Proxy, Protection Proxy, Smart Reference, Cache Proxy, Firewall Proxy, Counting Proxy, Synchronization Proxy

Implementation

400px-Proxy_pattern_diagram.svg.png
public class ProxySubject implements Subject {
    @Override
    public void getSomething() {
        if(RealSubject is available) 
            forward the call to it
        else {
            //do it here
        }
    }
}

Related Patterns

  • The Proxy pattern is often used in combination with the Forwarder-Receiver pattern to implement the 'stub' concept
  • The decorator is very similar in structure to Proxy. The major difference between the Decorator and Proxy patterns is intent.
  • An adapter provides a different interface to the object it adapts. In contrast, a proxy provides the same interface as its subject.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License