Pseudoclassical Decorators
We’re now going to examine a variation of the Decorator first presented in a JavaScript form in Pro JavaScript Design Patterns (PJDP) by Dustin Diaz and Ross Harmes.
Unlike some of the examples from earlier, Diaz and Harmes stick more closely to how decorators are implemented in other programming languages (such as Java or C++) using the concept of an “interface,” which we will define in more detail shortly.
Note
This particular variation of the Decorator pattern is provided for reference purposes. If you find it overly complex, I recommend opting for one of the simpler implementations covered earlier.
Interfaces
PJDP describes the Decorator pattern as one that is used to transparently wrap objects inside other objects of the same interface. An interface is a way of defining the methods an object should have; however, it doesn’t actually directly specify how those methods should be implemented.
Interfaces can also indicate what parameters the methods take, but this is considered optional.
So, why would we use an interface in JavaScript? The idea is that they’re self-documenting and promote reusability. In theory, interfaces also make code more stable by ensuring changes to them must also be made to the objects implementing them.
Below is an example of an implementation of interfaces in JavaScript using duck-typing, an approach that helps determine whether an object is an instance of that constructor/object based on the methods it implements.
// Create interfaces ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access