Search code examples
javadesign-patternsdecoratorproxy-pattern

If In Proxy Pattern we have interface instead of actual concrete Subject in Proxy class is it equivalent to Decorator Pattern


Proxy pattern delegates the request to the Real subject after doing some additional processing like applying checks if request needs to be processed or not based on may be some credential checks.

It has class diagram as below

enter image description here

Proxy class has a direct reference to the concrete Subject.

Decorator Pattern enriches the behavior of the component [like proxy it also does some additional processing and delegates the operation to the real component]. The class diagram of this pattern is similar to Proxy pattern with only difference being it has the reference to the interface of the component.

enter image description here

Having concrete real subject in Proxy class makes it difficult for unit testing as Classes should only be dependent upon interfaces and not the implementations. My Question is if Proxy pattern also has the reference to the interface exposed by the Real subject then will it be equivalent to the Decorator pattern. In such a case the class diagram of the proxy pattern will also become as below

enter image description here


Solution

  • It's all about the intent. Functionally, they will be equivalent, but the point of decorator is to add features to an object dynamically, while proxy just controls the access to the target object without adding any additional features to it.

    So the client of the proxy expects the same outcome as if it worked with the real object, while the client of the decorator leaves it to the decorator to execute any additional logic before and/or after delegating the call to the target.

    So, conceptually it seems that in your example you're still dealing with a proxy.