Singleton Design Pattern

https://refactoring.guru/design-patterns/singleton

Singleton design pattern categorized under creational design patterns. It is one of the most simple design pattern in terms of the modelling. In this article we are going to take a deeper look into the usage of the Singleton pattern.

  • Singleton controls object creation by limiting the number of objects to only one object. When an instance is wanted to be created from any class, if there is no instance created before, a new one is created. If it has been created before, the existing instance is used.
  • The Singleton design pattern ensures a class has only one instance and provide a global point of access to it.

One of the most common examples of singleton design patterns is the Logger, configuration settings, device driver objects.

We avoid creating global variables by using the singleton design pattern. In Singleton Pattern, when you create an object and want to create a new object after a while, the previously existed object is used. Even if other classes want to recreate that object, we keep it on the created object. Thanks to the Singleton Pattern, we create the object only when we need it.

https://refactoring.guru/design-patterns/singleton

That only a single instance of a class in your program to all clients use the Singleton pattern when necessary; for example, a single database object that can be shared by different sections of the program. If we re-create the database object on each client, we’re taking up memory space. This slows down the system.

We’re going to create a Singleton class. Singleton class have its constructor as private and have a static instance of itself.

Static member : A static member is created of the same type as the class and this contains the instance of the singleton class.

Declare a public static creation method. Static public method provides a public access point to a singleton object that is a static member. Static public method returns the instance to the client calling class.

Make the constructor of the class private. Private constructor will prevent anybody else to instantiate the Singleton class.

Computer Engineering