CHAPTER 12 Ensuring Correct Implementation of the Decorator Pattern


  • Using a decorator to neatly solve a real-world problem
  • Using a “fake” to stand in for the decorated object during unit tests
  • Using test-driven development to create a reliable decorator


You can find the code downloads for this chapter at on the Download Code tab. The files are in the Chapter 12 download and are individually named according to the filenames noted throughout this chapter.

The Decorator Pattern is a way of augmenting the capabilities of an object without changing it. You have already met some examples in this book. The memoization aspect in Chapter 8 decorates the function to which it is attached, giving the function the added ability to return a result without doing much work, when it is called with parameters it has seen before. When you set up a Jasmine spy with .and.callThrough(), you are decorating the spied-on function, augmenting it with the ability to report how many times it was called, and so on.

In this chapter, you will take the decorating process further. Instead of decorating an isolated function, you will decorate an object that has multiple, coordinated functions. You will also get more practice with the Promise object you encountered in Chapter 6. Finally, this will be another in-depth case study of test-driven development.

The case study is inspired by something ...

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.