How to define a Singleton?

A Singleton is a class that provides only one instance. This is different to a Static class as a static class cannot provide any instance(s). Say suppose, when you want to ensure that there is only one instance of a class in the lifetime of an application, you should consider creating a singleton class to ensure no more than one object is created. E.g. a valid case such as a user class for a desktop application.

There are two basic steps while creating a singleton class:

  1. Change the accessibility modifier on the constructor of class from public to private – this ensures that only current class can make an instance of it and no other class/code can create an instance using new keyword.
  2. Create a static property with a backing field. This will provide that one instance by checking whether an instance has been already created or not. If it’s not created, it creates a new instance by using the new keyword in it’s getter.

Let us see the above two steps in a sample code:

User.Instance can be used to access the only instance of User class. Above is a very simple example of a singleton class.

Some may think to use a static class over singleton but one should know the advantages of a singleton vs static class:

  • A singleton has an instance – that can be passed to other code as needed.
  • A singleton can have child objects. e.g. User instance can have a set of roles or other data associated with it.
  • A singleton supports object-oriented programming features
    • It can implement an interface
    • It can be inherited from

Use static class classes for common code library classes or when you don’t need any of the above features. Or in all other cases where you don’t need a single instance or static class, a normal class will do.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger