DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

6 1

JavaScript Design Patterns - Structural - Decorator

Image description

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:

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (6)

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
 
nhannguyendevjs profile image
Nhan Nguyen

Thanks for sharing 👏

Collapse
 
artydev profile image
artydev

Very instructive :-)

Collapse
 
jangelodev profile image
João Angelo

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay