Ashish Patel: Notes

Atom feed

Recently added: Xunit, Publisher subscriber pattern, Request reply pattern, Middleware pattern, Command 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:45:03+05:18, updated 2020-08-23T12:24:12+05:18 · History · Edit