...

/

Superman Problem

Superman Problem

Correctly implementing a singleton pattern in C#.

Superman Problem

You are designing a library of superheroes for a video game that your fellow developers will consume. Your library should always create a single instance of any of the superheroes and return the same instance to all the requesting consumers.

Say, you start with the class Superman. Your task is to make sure that other developers using your class can never instantiate multiple copies of superman. After all, there is only one Superman!

widget

Solution

You probably guessed we are going to use the Singleton pattern to solve this problem. The Singleton pattern sounds very naive and simple but when it comes to implementing it correctly in C#, it’s no cake walk.

Singleton Pattern

First let us understand what the pattern is. A singleton pattern allows only a single object/instance of a class to ever exist during an application run.

There are two requirements to make a class adhere to the singleton pattern in C#:

  • Declaring the constructor of a class private. When you declare the Superman class's constructor private then the constructor isn't visible outside the class or in its subclasses. Only the instance and static methods of the Superman class are able to access the constructor and create instances of the Superman class.

  • The second trick is to create a public static method usually named getInstance() to return the only instance. We create a private static object of the class Superman and return it via the getInstance() method. We can control when to instantiate the lone static private instance.

Almost Lazy Initialization

Applyin ...

Access this course and 1400+ top-rated courses and projects.