Classification of design patterns : Creational Design Patterns

http://knowledge-cess.com/classification-of-design-patterns-creational-design-patterns/

Before reading further , let us first understand what are design patterns read part 1 of this article

Creational Design Pattern

Object creation is a very common pattern we need to use almost for all complex objects. Object creation is not just allocating a memory and use it, we may need to consider lot of aspects while creating an object.

Creational design pattern solves this problem by following a sophisticated approach, typically creational design patterns will be used for initialising hardware configuration, database connections , Logger object.

Creational design patterns are important to use because they follow SOLID Principles closely. It allows long term flexibility, it allows more decoupling and easily testable.

Let us look into some of the important creational design patterns

Singleton Pattern

We have to identify a scenario where we may need to maintain only one object, even if you try to create an object, the program should not allow to create new object instead it has to return only one object.

Singleton pattern is meaningful where multiple objects doesn’t make any sense. Taking few scenarios here for example , DBConnectionHandler, MQManager for managing Queue connections, these are classical examples where having multiple objects has no meaning.

Example of Singleton Pattern in Javascript

<code>class MQManager {
  constructor() {
    this.amqpProducerConn = null;
    this.amqpConsumerConn = null;
    this.producerChannel = null;
    this.consumerChannel = null;
  }
  createProducerConnection(onConnectSuccess, onConnectFail) {
  }

  createConsumerConnection(onConnectSuccess, onConnectFail) {
  }
  createProducerChannel(connection) {}
  createConsumerChannel() {}
  enqueueJob(queueName, jobDetails) {}
  dequeueJob(queueName, consumerCallback) {}
  closeProducerConnectionOnErr(err) {}
  closeConsumerConnectionOnErr(err) {}
};
module.exports = (() => {
  let instance;
  function getInstance() {
    //TO RESTRICT CREATING SINGLE OBJECT 
    if (instance === undefined) {
      instance = new MQManager();
    }
    return instance;
  }
  // Public API definition
  return {
    getInstance
  };
})();</code>

The above class we can import as follows

<code>const MQManager = require('./mqManager').getInstance();</code>

Read More About Creational Design Pattern

Thanks to refactoring.guru for wonderful images - https://refactoring.guru/design-patterns/