Łukasz Rzeszotarski Łukasz Rzeszotarski - 11 months ago 95
Java Question

Differences between Proxy and Decorator Pattern

Can you give any good explanation what is the difference between Proxy and Decorator?

The main difference I see is that when we assume that Proxy uses composition and Decorator uses aggregation then it seems to be clear that by using multiple (one or more) Decorators you can modify/ add functionalities to pre-existing instance (decorate), whereas Proxy has own inner instance of proxied class and delegates to it adding some additional features (proxy behaviour).

The question is - Does Proxy created with aggregation is still Proxy or rather Decorator? Is it allowed (by definition in GoF patterns) to create Proxy with aggregation?

Answer Source

Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object.


Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way, whereas Decorator is assigned to the subject at runtime, knowing only subject's interface.