DEV Community

Cover image for Decorator-Pattern | Javascript Design Pattern Simplified | Part 5
Aakash Kumar
Aakash Kumar

Posted on

Decorator-Pattern | Javascript Design Pattern Simplified | Part 5

As a developer, understanding various JavaScript design patterns is crucial for writing maintainable, efficient, and scalable code. Here are some essential JavaScript design patterns that you should know:

Factory Pattern

The Decorator pattern allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

Example:
`
class Coffee {
cost() {
return 5;
}
}

class MilkDecorator {
constructor(coffee) {
this.coffee = coffee;
}

cost() {
return this.coffee.cost() + 2;
}
}

let coffee = new Coffee();
coffee = new MilkDecorator(coffee);

console.log(coffee.cost()); // 7
`

Real World Example

Online Store Product Customization

Real-World Scenario: In an online store, customers can customize products by adding features (e.g., extra warranty, gift wrapping). The Decorator pattern allows these features to be added dynamically.

Define the Base Class:

class Product {
  constructor() {
    this.price = 100;
  }

  getPrice() {
    return this.price;
  }
}
Enter fullscreen mode Exit fullscreen mode

Create Decorator Classes:

class WarrantyDecorator {
  constructor(product) {
    this.product = product;
  }

  getPrice() {
    return this.product.getPrice() + 20;
  }
}

class GiftWrapDecorator {
  constructor(product) {
    this.product = product;
  }

  getPrice() {
    return this.product.getPrice() + 5;
  }
}
Enter fullscreen mode Exit fullscreen mode

Use the Decorator Pattern:

let myProduct = new Product();
myProduct = new WarrantyDecorator(myProduct);
myProduct = new GiftWrapDecorator(myProduct);

console.log(myProduct.getPrice()); // 125 (100 + 20 + 5)
Enter fullscreen mode Exit fullscreen mode

Use Cases of the Decorator Pattern

1. Adding Responsibilities Dynamically: When you need to add responsibilities to objects at runtime, the Decorator pattern provides a flexible alternative to subclassing.

2. Combining Behaviors: It allows combining several behaviors by applying multiple decorators in a flexible and reusable way.

3. Enhancing Core Objects: Useful for enhancing core objects in libraries or frameworks without modifying the original code.

Conclusion

Understanding these design patterns and knowing when to apply them can greatly improve your coding skills and make you a more effective full-stack developer. They help in creating robust and maintainable code.

Mastering these patterns will help you build better software.

Happy Coding! 🧑‍💻

Connect with Me 🙋🏻: LinkedIn

Top comments (0)