Decorator

Add responsibilities to objects dynamically.

  • Decorator pattern allows to add a new functionality to the existing object without altering their structure and it acts as a wrapper to the existing class.

  • This pattern dynamically changes the functionality of the object at runtime without impacting the existing functionality of the object.

  • In short, it adds the additional functionality to the object by wrapping it.

  • Decorator is an object that adds feature to another object.

  • Most frequently used in JavaScript.

EX:
var User = function(name) {
    this.name = name;
 
    this.say = function() {
        console.log("User: " + this.name);
    };
}
 
var DecoratedUser = function(user, street, city) {
    this.user = user;
    this.name = user.name;  // ensures interface stays the same
    this.street = street;
    this.city = city;
 
    this.say = function() {
        console.log("Decorated User: " + this.name + ", " +
                   this.street + ", " + this.city);
    };
}

function run() {
 
    var user = new User("Kelly");
    user.say(); // User: Kelly
 
    var decorated = new DecoratedUser(user, "Broadway", "New York");
    decorated.say(); // Decorated User: Kelly, Broadway, New York
}

Last updated