Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Structural design patterns

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
}
PreviousCompositeNextFacade

Last updated 5 years ago

Was this helpful?