Duc Tran

Web Developer

Freelancer

Blogger

Photographer

Duc Tran

Web Developer

Freelancer

Blogger

Photographer

Blog Post

Singleton Pattern in Javascript

13th March 2020 Design Patterns
Singleton Pattern in Javascript

Design patterns are reusable solutions to commonly occurring problems in software design. It is the most important thing if you want to become a Senior Software Engineer and sure, you will meet it in several interviews 😀 😀 .

Singleton is one of the most popular patterns in design pattern, because Singleton is useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’. So, let’s find out Singleton Pattern and how to use it in Javascript with me (Singleton Javascript).

Definition

Ensure a class has only one instance and provide a global point of access to it.
Frequency of use (in JavaScript):

design pattern singleton javascript
high

Sample code in JavaScript

The Singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn’t have a name.

The getInstance method is Singleton’s gatekeeper. It returns the one and only instance of the object while maintaining a private reference to it which is not accessible to the outside world.

const singleTon = (() => {
  let instance;

  const initFn = () => {
    let number = 0;

    return {
      getValue: () => number,
      setValue: x => { number = x; }
    };
  };

  return {
    getInstance: () => {
      if (!instance) instance = initFn();
      return instance;
    }
  }
})();

Lets run this code above

const sgtA = singleTon.getInstance();
sgtA.getValue(); // return 0;
sgtA.setValue(4); // the value (4) now will be stored
sgtA.getValue(); // return 4;
const sgtB = singleTon.getInstance();
sgtB.getValue(); // return 4; sgtB now has the same instance with sgtA
sgtB === sgtA; // true

Conclusion

It’s quite likely that you will run into overwhelming online literature on how singletons are bad for object oriented designs. The idea is to use singletons where it doesn’t affect the state of the application, because if you fail to follow, then testing goes right out the window. This severely limits their usage in big applications. Most developers agree that global state is bad, but they love them too much to look at its bad sides while others go extreme lengths to avoid using global states. Whether singletons are good or bad, understanding this fundamental design pattern and adding it to your programming toolkit is always a wise idea.

Write a comment