Skip to content

Latest commit

 

History

History
20 lines (11 loc) · 1.01 KB

README.md

File metadata and controls

20 lines (11 loc) · 1.01 KB

Singleton Design Pattern

Overview

Singleton pattern is one of the creational design pattern. This pattern provides one of the best ways to create an object.

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

It ensures that only a single instance of the class is available throughout the application.

Implementation

All implementations of the Singleton have these two steps in common:

  • Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
  • Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.

Examples

Here a logger is implemented using this pattern.