remi bourgarel
remi bourgarel

Reputation: 9389

When should I use decorator / observer?

There is these two pattern : observer and decorator. Both enables me to add an action after something was done (or before for the decorator). But their implementation differs. So when should I use a decorator or an observer.

So far I came up with this :

For instance in a booking level I have a booking entity, the first service will create the booking and mark the accomodation as not available :

Am I right ?

Upvotes: 2

Views: 2539

Answers (2)

lbalazscs
lbalazscs

Reputation: 17784

These two patterns are not similar. You should use Decorator if you need to additional responsibilities to an object while keeping the same interface. I don't see why would you need to keep the same interface in this case, therefore I am against Decorator.

Observer is fine when you want to be notified of a change in another object (for example to "add an action after something was done"), although there could be simpler ways.

Upvotes: 2

Tom
Tom

Reputation: 986

Observer is a behavioral pattern. Decorator is a structural pattern.

Using observer implements event handling (it binds some method calls of different classes with each other). Using decorator you can change (extend) features of some object at a runtime (it changes the objects themselves - thanks to polymorphysm, so same methods may be overridden etc).

In your example booking application I would use both patterns (as you presented it).

Upvotes: 1

Related Questions