Sobes.tech
Junior — Middle

Explain the differences between the Decorator pattern and functions in terms of their usage and purpose.

sobes.tech AI

Answer from AI

The Decorator pattern is a structural design pattern that allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects. It is used to extend functionality without modifying the original class code.

Functions in programming are blocks of code that perform a specific task and can return a result. In the context of Node.js, functions are often used for data processing, callbacks, middleware, etc.

Main differences:

  • Purpose: Decorator — to extend object behavior, functions — to perform logic.
  • Usage: Decorator wraps an object, adding functionality; functions are called to perform a task.
  • Structure: Decorator — wrapper object; functions — code blocks.

Example of a Decorator in JS:

function loggerDecorator(fn) {
  return function(...args) {
    console.log('Function call with arguments:', args);
    return fn(...args);
  };
}

function sum(a, b) {
  return a + b;
}

const decoratedSum = loggerDecorator(sum);
console.log(decoratedSum(2, 3)); // Logs the call and returns 5

Here, the loggerDecorator function acts as a decorator, extending the behavior of the sum function.

Explain the differences between the Decorator pattern… - sobes.tech