JavaScript Design Patterns

Javascript design pattern

JavaScript Design Patterns: Solutions for Efficient and Reusable Code

Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. Here are some common design patterns in JavaScript:

1. Module Pattern

The Module pattern is used to create private and public encapsulation for classes in JavaScript.

var testModule = (function () {
  var counter = 0;
  return {
    incrementCounter: function () {
      return counter++;
    },
    resetCounter: function () {
      console.log('counter value prior to reset: ' + counter);
      counter = 0;
    }
  };
})();

2. Prototype Pattern

The Prototype pattern is an object-based creational design pattern. In this, we use a sort of a “skeleton” of an existing object to create or instantiate new objects.

var vehiclePrototype = {
  init: function (carModel) {
    this.model = carModel;
  },
  getModel: function () {
    console.log('The model of this vehicle is..' + this.model);
  }
};

3. Observer Pattern

The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs. This pattern is the cornerstone of event driven programming.

class Subject {
  constructor() {
    this.observers = [];
  }
  subscribe(observer) {
    this.observers.push(observer);
  }
  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => observer !== obs);
  }
  fire(action) {
    this.observers.forEach(observer => {
      observer.update(action);
    });
  }
}

4. Singleton Pattern

The Singleton pattern restricts the instantiation of a class to a single instance. It is used where only a single instance of a class is required to control actions.

var Singleton = (function () {
  var instance;
  function createInstance() {
    var object = new Object('I am the instance');
    return object;
  }
  return {
    getInstance: function () {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

5. Factory Pattern

The Factory pattern is another creational pattern concerned with the notion of creating objects. Where it differs from the other patterns in its category is that it doesn’t explicitly require us to use a constructor.

class BallFactory {
  constructor() {
    this.createBall = function(type) {
      let ball;
      if (type === 'football' || type === 'soccer') ball = new Football();
      else if (type === 'basketball') ball = new Basketball();
      ball.roll = function() {
        return `The ${this._type} is rolling.`;
      };
      return ball;
    };
  }
}

These are just a few of the design patterns available in JavaScript. Understanding these patterns can help you solve complex problems with clean, organized, and reusable code.

Comments

Popular posts from this blog

GTM for SFCC

Java Interview Questions

JavaScript and Deployment