+7

The Decorator Design Pattern in JavaScript

In this article, we'll learn what is the Decorator Design Pattern in JavaScript, why its useful...

What is the Decorator Pattern?

The Decorator Design Pattern is a way of adding additional functionality to an existing object without modifying its structure. This is done by wrapping the existing object with an outer object to extend its behavior.

Why is the Decorator Design Pattern useful?

The Decorator Design Pattern is useful because it allows us to easily add additional functionality to an existing object without having to modify its structure. This is especially useful when the functionality we need is complex or would require a lot of code to implement.

Example in Javascript

Logging Decorator

In this example, we will create a Logging Decorator that logs a message every time a function is called.

// Create the base function
function getData() {
  // Do something
}

// Create the LoggingDecorator
function LoggingDecorator(fn) {
  return function () {
    console.log('Logging...');
    fn();
  }
}

// Decorate the function
let decoratedFn = LoggingDecorator(getData);

// Call the decorated function
decoratedFn(); // Logs 'Logging...'

Caching Decorator

In this example, we will create a Caching Decorator that stores the result of a function call in a cache. We will also add a mechanism to check if the result is already present in the cache and return its value without calling the function.

// Create the base function
function getData() {
  // Do something
}

// Create the cache
let cache = {};

// Create the CachingDecorator
function CachingDecorator(fn) {
  return function () {
    // Check if the result is in the cache
    if (cache[fn]) {
      return cache[fn];
    }

    // Call the function and store the result in the cache
    let result = fn();
    cache[fn] = result;
    return result;
  }
}

// Decorate the function 
let decoratedFn = CachingDecorator(getData);

// Call the decorated function
decoratedFn();

Throttling Decorator

In this example, we will create a Throttling Decorator that limits a function to run no more than once in a certain amount of time.

// Create the base function 
function getData() {
  // Do something
}

// Create the ThrottlingDecorator
function ThrottlingDecorator(fn, delay) {
  let lastCallTime;
  return function () {
    // Check if the function was called before 
    if (lastCallTime && (Date.now() - lastCallTime) < delay) {
      return;
    }

    // Call the function and store the time
    lastCallTime = Date.now();
    fn();
  }
}

// Decorate the function
let decoratedFn = ThrottlingDecorator(getData, 500);

// Call the decorated function
decoratedFn();

Conclusion

The Decorator Design Pattern is a way to easily extend the functionality of an existing object without having to modify its structure. We've seen some code samples and can see how this pattern makes adding additional functionality to objects very easy.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí