Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator pattern versus sub classing

I can solve the problem of adding functionality by adding sub classing then why should I use decorator pattern what's the real advantage of decorator pattern ?

like image 390
Gainster Avatar asked Jan 30 '11 12:01

Gainster


People also ask

What is the difference between decorator and Strategy pattern?

The strategy pattern allows you to change the implementation of something used at runtime. The decorator pattern allows you augment (or add to) existing functionality with additional functionality at run time.

What is the difference between chain of responsibility and decorator patterns?

The chain-of-responsibility pattern is structurally nearly identical to the decorator pattern, the difference being that for the decorator, all classes handle the request, while for the chain of responsibility, exactly one of the classes in the chain handles the request.

What is the decorator pattern also known as?

A Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically". In other words, The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime. The Decorator Pattern is also known as Wrapper.

When should we use the decorator pattern?

The Decorator pattern is best when the decorators modify the behavior of the methods in the interface. A decorator can add methods, but added methods don't carry through when you wrap in another decorator.


1 Answers

from Decorator pattern at wikipedia

The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime.

The whole point of decorator pattern is to dynamically add additional behaviour/functionality, which is of course not possible at design time.

from the same article:

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.

like image 158
sloth Avatar answered Sep 18 '22 05:09

sloth