Design Pattern in simplicity: Decorator Pattern

Kenneth Cheung
< />
Published in
2 min readMar 16, 2018

In case you don’t know what this series is about. Here is the link to the first Article in the series. The first section of that article is the motivation and introduction of the series. I hope it helps you to understand more about the objective of this series.

Decorator Pattern

Decorator Pattern is a common and useful pattern. When you have several objects, functions or views, you can create a base form and decorate the base form with additional functionality(decorator).

OK, I know it is great, but how to do it? Decorator is similar to the concept of Higher-order function. Decorator takes the base form as an argument, and puts some decoration on it and return it.

Example

You want to build a button UI. The Button have several independent behaviors like:

  1. Hover popover information.
  2. Action confirm.
  3. Trigger some specific tracking code.

You can design your button like this:

var PopoverButton = new PopoverDecorator(
new Button()
);
// or with React Style
// const PopoverButton = withPopover(Button);
var PopoverActionConfirmButton = new PopoverDecorator(
new ActionConfirmDecorator(
new Button()
)
);
// etc...

The PopoverDecorator class takes whatever Button as argument and return the decorated button, so does ActionConfirmDecorator. This approach increase the cohesion of the Button. By Separating the specific behavior of the Base form, you can easily reuse and extension these functionality in the future.

What a elegant pattern, isn’t it?

Conclusion

This article is a very brief introduction for Decorator Pattern. It covers the core idea of Decorator Pattern. If you want to know more about it, you can checkout the following references section.

Decorator Pattern is one of my favorite pattern. Higher-order function is a very powerful concept. I use it a lot for designing React Component and utilities function in my project and I hope it makes my colleague happier. Thanks for reading!

References

--

--