Search code examples
design-patternsproxy-pattern

Proxy Pattern - real subject not hidden from client


I was reading about Proxy on DoFactory and Wikipedia, and Stack Overflow, of course. Everything is clear, except Real Subject. On DoFactory, Proxy is defined as:

Provide a surrogate or placeholder for another object to control access to it. (added bold font)

If its purpose is to control access to Real Subject, why Real Subject is not hidden from the Client ?

Here is a UML Diagram of Proxy:

Proxy UML

In code example, Real Subject is defined as:

class RealSubject : Subject
{
    ...
}

Client creates an instance of Proxy and "controls access" to Real Subject through it:

Proxy proxy = new Proxy();
proxy.Request();

But (from several example that I saw) there is nothing that stops Client from instantiating Real Subject and accessing its methods. I would like to know why is that?


Solution

  • You could certainly implement the Proxy pattern so that RealSubject is invisible to Client. Indeed, if every client is expected to use only the proxy, that would be a good OO approach.

    On the other hand, a proxy is typically used to increase efficiency or security, or to add functionality such as lazy loading. If there are many clients, some of them may not need what the proxy adds, and will use RealSubject directly.

    In the case of a library API, RealSubject might be exposed (public) to allow any client to implement its own proxy. RealSubject is then visible to the client, even though the client only uses its proxy.

    Another scenario is that Proxy may only provide a partial interface to RealSubject. Take the example of a protection proxy that controls access to RealSubject. After the client is authenticated, it may be allowed direct access to RealSubject, and the proxy can be disposed of.

    As you can see, the value of a proxy often depends on the client(s) involved. Some clients may use it exclusively, in which case RealSubject can be hidden. Other clients may use it temporarily, while other clients may not use it at all.