JavaScript design patterns: Decorators

JavaScript design patterns: Decorators

·

2 min read

I have explained about Object Creation pattern in JavaScript. Object creation pattern. So let's learn about the Decorator Pattern.

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 behavior. But how they achieve this behavior 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.


Removal.AI - [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Visit -> Removal.AI


Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!