An Intro to the Singleton Design Pattern in Angular.
Design patterns are best practices and reusable solutions to recurring software design problems.
Design patterns are independent of a programming language. They are ways, ideas or approaches that help us write efficient code. The patterns have three main types, which are: Creational, Structural and Behavioral design patterns.
In this article you will learn how to utilize the singleton design pattern (Creational design pattern — Focused on object creation mechanisms).
What is the Singleton Design Pattern?
An object-oriented design pattern used to ensure that we always have one or a single instance of a class; Meaning that you cannot create multiple objects of that class.
A notable detail about this pattern is that the single instance in the context of Angular, shall be available to the entire application or to a specific module if provided within a specific context/scope using dependency injection — more on this pattern in a separate article.
In Angular, this design pattern is achieved through the provision of a class in a root, shared or scoped NgModule/Components
’s providers configuration.
Following is a practical example.
Note how we have encapsulated the creation of a session by using static members and a private constructor in the singleton.ts
file.