Tag Archives: Decorator Pattern

Decorator Pattern – Design Pattern

Today We will be discussing about decorator pattern. Question arises what is decorator pattern what is need of such pattern, where we can implement it.

Consider a Restaurant or simply coffee shop, where you have lot of menu items and some of items are customizable as per the need of customer. and prices varies as per the commodities involved in making it.

In this scenario we can not provide all price options just by inheriting a class, subclass each behavior and extending each class with some super class ? Why just due to commodity prices varies, and you can’t go every time to update it in code, and each customer may want different amount of commodities involved in making of that customized item(e. g. A coffee having high amount of coffee and involving no sugar, without milk)

In this scenario Decorator pattern comes to picture. Which allows us to attaches additional responsibilities to an object(In our case Coffee may be our object) dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The Decorator Pattern provides an alternative to subclassing for extending behavior. It involves a set of decorator classes that are used to wrap concrete components.

Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)

Decorator changes behavior by adding new functionality before and/or after (or even in place of) method calls to the component.

You can think of some kind like it works on chaining principle, that an object can be wrapped multiple time by Another object and vice versa, as both of then are using the Same parent type of object in there constructor.