Design Patterns — Singleton

Before I get into this specific design pattern, I’d like to talk a bit about what a design pattern is and why it is important as a programmer. Let’s get started!

Design Pattern

When I first began learning to code, I never really thought about things such as design patterns and algorithms. I just focused on learning the syntax and solving simple coding problems, overall I was just excited to be learning a new skill! But… as I progressed, I soon realized that design patterns and solving algorithms are probably two of the most important things a professional software engineer needs to know! In a software engineering job, you aren’t just building websites for fun, you’re building massive web applications with complex systems that need to run perfectly if you want your users to have a great experience.

Singleton Design Pattern

The Singleton Design pattern is implemented to only allow one instantiation of a class object. The typical goal of this pattern is to manage the global state of your application. A few real world examples could be using a singleton as the source of config settings for a web app, on the client-side for initiating an API, and to store data in memory on the client-side. Another important thing to note about a singleton is that it should be immutable by any outside code, and you should be certain that no more than one can be instantiated.

ES5 singleton example
creating an instance
testing in console
ES6 example
  1. use of const — This prevents our UserStore from being reassigned in the future
  2. use of Object.freeze() — This prevents the objects methods from being changed, and also prevents new methods from being added to it.
ES6 class example
complete prevention


Software Engineer - JavaScript, Ruby, React, Ruby on Rails

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store