· 1 min read Comments

Brief guide to JavaScript design patterns: Decorators

  1. Calligraphy Authors's Headshot
    Rahulism

    Owner


Table Of Contents


The decorator pattern is a structural design pattern that attaches additional responsibilities to an object dynamically.

What is a decorator pattern?

The decorator pattern is a structural design pattern that attaches additional responsibilities to an object dynamically. This is a concept of adding extra functionality to the original structure.

However, keeping it decoupled and clean.

The decorator pattern adds new behaviour to objects dynamically at runtime wrapping itself around the original object. Multiple decorators can add or override functionality to the original object.

Example:

function Fruit() {
    this.cost = function () { return 100; }; 
}
function Orange(fruit) {
    var v = fruit.cost(); 
    fruit.cost = function () {
        return v + 75; 
    }
}
function Apple(fruit) {
    var v = fruit.cost(); 
    fruit.cost = function () {
        return v + 200; 
    }; 
}    
var fruit = new Fruit(); 
Orange(fruit); 
Apple(fruit); 
console.log('Total Cost', fruit.cost()); // Total Cost: 375

It looks like Inheritance?

Inheritance and the decorator pattern allows changing object behaviour. But how they achieve this behaviour change is where inheritance and the decorator pattern are different.

The decorator would be difficult to implement when derived classes need to access non-public fields or methods in the parent class. The decorator pattern eliminates the problem of exploding class hierarchy encountered with inheritance.


Share on:
Ashish Lahoti avatar
About Rahulism
I’m a front-end Developer and Blogger. Focused more on User Experience. I’m Passionate about startups