DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Structural - Decorator

Decorator is a structural design pattern that allows us to attach new behaviors to objects by placing them inside special wrapper objects containing them.

In the example below, we use a decorator to extend behavior in Facebook Notifications.

class Notification {
  constructor(kind) {
    this.kind = kind || "Generic";
  }

  getInfo() {
    return `I'm a ${this.kind} Notification`;
  }
}

class FacebookNotification extends Notification {
  constructor() {
    super("Facebook");
  }

  setNotification(msg) {
    this.message = msg;
  }

  getInfo() {
    return `${super.getInfo()} with the message: ${this.message}`;
  }
}

class SMSNotification extends Notification {
  constructor() {
    super("SMS");
  }

  getInfo() {
    return super.getInfo();
  }
}

export { FacebookNotification, SMSNotification };
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Use this pattern when adding extensions to an object in runtime without affecting other objects.


I hope you found it helpful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Top comments (6)

Collapse
ย 
artydev profile image
artydev โ€ข

Very instructive :-)

Collapse
ย 
efpage profile image
Eckehard โ€ข

What's the difference to inheritance?

Collapse
ย 
budgiewatts profile image
John Watts โ€ข

You can use the same decorator to provide the same functionality to multiple classes if they implement a common interface without having to extend all of those classes for what might be a niche use case.

Collapse
ย 
efpage profile image
Eckehard โ€ข

If you need the same functionality in multiple classes itยดs a sign your hierarchy needs some update. You should implement common functions in a parent class, not again and again in the childs using decorators.

Thatยดs OOP bottom-up!

Thread Thread
ย 
nhannguyenuri profile image
Nhan Nguyen โ€ข

Thanks for sharing ๐Ÿ‘

Collapse
ย 
jangelodev profile image
Joรฃo Angelo โ€ข

Hi Nhan Nguyen,
Your tips are very useful
Thanks for sharing