Blog#136: The Decorator Design Pattern in JavaScript

image.png

Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

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.

And Finally

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊


The main goal of this article is to help you improve your English level. I will use Simple English to introduce to you the concepts related to software development. In terms of IT knowledge, it might have been explained better and more clearly on the internet, but remember that the main target of this article is still to LEARN ENGLISH.

NGUYỄN ANH TUẤN

Xin chào, mình là Tuấn, một kỹ sư phần mềm đang làm việc tại Tokyo. Đây là blog cá nhân nơi mình chia sẻ kiến thức và kinh nghiệm trong quá trình phát triển bản thân. Hy vọng blog sẽ là nguồn cảm hứng và động lực cho các bạn. Hãy cùng mình học hỏi và trưởng thành mỗi ngày nhé!

Đăng nhận xét

Mới hơn Cũ hơn