Decorator or Wrapper

The Decorator pattern (also known as Wrapper) is useful when you want to add additional responsibilities or functionalities to an object in a dynamic way. Let's consider a simple example, which we will illustrate with some React code. (Don't worry if you do not know this framework; the example will be easy to understand). Suppose we want to show some element on screen, and for debugging purposes, we want to show a thin red border around the object. How can you do it?

If you were programming using OO, you would probably have to create a new subclass, with the extended functionality. For this particular example, you may just provide some attribute with the name of some CSS class that would provide the required style, but ...

Get Mastering Javascript Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.