JavaScript Design Patterns — Structural — Decorator

Nhan Nguyen
1 min readMay 3, 2024

--

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

👉 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:

--

--

Nhan Nguyen
Nhan Nguyen

No responses yet