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

点点圈 提交于 2019-12-05 09:57:56

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.

Yes. If you look at structure, it will be same for both Decorator and Proxy. Only intent is different.

Decorator:

  1. Add behaviour to object at run time. Inheritance is the key to achieve this functionality, which is both advantage and disadvantage of this pattern.
  2. It modifies the behaviour of interface.

e.g. (with chaining ) : java.io package classes related to InputStream & OutputStream interfaces

FileOutputStream fos1 = new FileOutputStream("data1.txt");  
ObjectOutputStream out1 = new ObjectOutputStream(fos1);

Consequences

  1. Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
  2. Decoration adds functionality to objects at runtime which would make debugging system functionality harder.

Proxy:

  1. Use it for lazy initialization, performance improvement by caching the object and controlling access to the client/caller. It may provide alternative behaviour or call real object. During this process, it may create new Object.
  2. Unlike Decorator, which allows chaining of objects, Proxy does not allow chaining.

e.g.: java.rmi package classes

Key takeaways:

  1. Proxy provides the same interface. Decorator provides an enhanced interface.
  2. Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.

Useful links:

Decorator_pattern from wikiepdia

decorator from sourcemaking

decorator-pattern from oodesign

Proxy_pattern from wikipedia

proxy from sourcemaking

proxy-pattern from oodesign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!