Ashish Patel: Notes

Atom feed

Recently added: Introduction, Abstraction, Xunit, Publisher subscriber pattern, Request reply pattern

Decorator Pattern

Decorator Pattern is designed to provide you with a clean way of extending abilities of your original Object or Component, without impacting its initial state or structure.

// User.js

class User {
  constructor(firstName, lastName, title) {
    this.firstName = firstName
    this.lastName = lastName
    this.title = title
  }

  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}
// UserDecorator.js

class UserDecorator {
  constructor(user) {
    this.user = user
  }

  getFullName() {
    return this.user.getFullName()
  }
}
// UserFullNameWithTitleDecorator.js

class UserFullNameWithTitleDecorator extends UserDecorator {
  getFullName() {
    return `${this.user.title} ${this.user.getFullName()}`
  }
}
// App.js

const user = new User('Arthur', 'Frank', 'Mr')
user.getFullName()

const decoratedUser = new UserFullNameWithTitleDecorator(user)
decoratedUser.getFullName()

Created 2019-01-23T11:57:03+05:30, updated 2020-08-23T12:36:12+05:30 · History · Edit