Question

I was going through the proxy pattern and noticed that the Proxy class also implements the Subject interface, which is implemented by the concrete implementations or the Subject classes as well.

Can anyone provide a reason why we need to do so ?

We could have created a function in the proxy class and call the subject methods inside this function. Then the client code can call this proxy class function and the appropriate methods could be called.

Was it helpful?

Solution

Following the way you suggested would have the same result but I would not call it a proxy, I would call it a wrapper. Using the proxy design pattern with an interface would be preferable IMHO, because the client could be agnostic of which class is actually used to execute the respective functionality. The client would only see the subject interface class and not know anything about the Proxy or the RealSubject concrete classes. This would be important for long-term maintenance of the code.

Of course a design pattern is not something strict that you should follow in order to be "right". It is a guideline for common software engineering scenarios. Therefore, you should implement it in the way it is most convenient for you.

Just to avoid misunderstandings, I clarify that I used this as a reference for the proxy design pattern.

OTHER TIPS

Proxy should on the surface, be all means, behave like it is a real object you are asking for. You shouldn't be able to tell whether you are using proxy object or real object which is hidden by proxy. That's the reason why proxy implements the Subject class.

Proxy can encapsulate logic which should not be visible to a user. For example logging, statistics, connecting to a remote server, and so forth. A user of the class should not be bothered with what's going on on the background.

If you are only one who uses code written by you then you can disobey this pattern as you will always know what's going on there.

Example from real life: take, for instance, an internet connection. A user just wants to have it working, he should not be bothered will connecting to proxy server. For him, internet connection is a black box.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top