Differences between Proxy and Decorator Pattern

Łukasz Rzeszotarski picture Łukasz Rzeszotarski · Sep 4, 2013 · Viewed 38.3k times · Source

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

cdunn2001 picture cdunn2001 · Aug 8, 2014

The real difference is not ownership (composition versus aggregation), but rather type-information.

A Decorator is always passed its delegatee. A Proxy might create it himself, or he might have it injected.

But a Proxy always knows the (more) specific type of the delegatee. In other words, the Proxy and its delegatee will have the same base type, but the Proxy points to some derived type. A Decorator points to its own base type. Thus, the difference is in compile-time information about the type of the delegatee.

In a dynamic language, if the delegatee is injected and happens to have the same interface, then there is no difference.

The answer to your question is "Yes".