Decorator pattern (Ever heard of writing wrappers?)

Decorator pattern (Ever heard of writing wrappers?)

Hey. Do you want to attach new behaviors to objects on the runtime? You can place these objects inside special wrapper objects which contains such new behaviors :D. -- Decorator pattern


This is a continuation of the software design pattern series. You can checkout the previous posts from my software-design-pattern series


Decorator pattern

Ever been in a situation where you need to add additional functionalities to a particular object, but not to an entire class? Suppose if you need to add for the entire class of objects, you could extend the existing class and work on the extended class but if you want just some additional features for a particular object you could go for the decorator pattern.


Ok. So where can I use Decorator pattern?

When you want to
-> Add additional functionalities to an object dynamically.
-> Remove functionalities from an object dynamically
-> Avoid a lot a sub-classing for varying additional functionalities.


Example: Ordering a Pizza. Decorating it with Double cheese layer, adding some Peri-Peri Chicken, adding some onions and so on. Combinations go exponential.


Cool. So how to implement Decorator pattern?

In decorator pattern, Four components gets involved excluding the Client.

  • Component interface
  • Concrete Component
  • Base Decorator
  • Concrete Decorators

-> Component interface

The Interface which should be implemented by both the Concrete component and the Base Decorator

-> Concrete Component

The Component Class implementing the Component interface which can be decorated

-> Base Decorator

The abstract class implements the Component interface. This has the field referencing a wrapped object. This needs to be extended by all the decorators.

-> Concrete Decorators

The decorator classes extending or implementing the base decorator class. This holds all the extra behaviors to be added to the object to be wrapped. This overrides the methods of the base decorator and executes it's own logic before or after calling the parent method.


Design Structure

image.png

photo courtesy: link


Sample code

Output

Cost of simple pizza :: 200.0
Cost of double cheese pizza :: 280.0
Cost of double cheese pizza with peri peri chicken toppings :: 380.0

As seen in the code example, the pizza object could be decorated dynamically depending on the runtime thus increasing the getCost() behavior as needed.


Hope this helps. Looking forward to more learning and sharing. Cheers :)

Connect, share and text me about your views. We can have some discussion :)


Stay connected:

Connect on Twitter

Connect on Linkedin


ps: Article cover courtesy: Photo by Arun Kuchibhotla on Unsplash

Did you find this article valuable?

Support Build with Sammie by becoming a sponsor. Any amount is appreciated!