Description

Singleton is a design pattern which ensures that a class has only one instance.

Application

Facebook for example, logs your activity such as logins, likes and comments. Would it make sense if it had to instantiate a logger for each activity separately? Think about it in terms of performance - 10 people liking, commenting and logging out of the platform, that’s 10*3 when it can be 10*1 which will be lighter and faster.

An analogy: How would you feel, if you had to wait in a line, welcoming people to your house as they came through and you had to ask them 3 questions before letting them in:

  1. Name
  2. Age
  3. Favorite hobby

Easy, right? Now, imagine there are 3 lines of people and each will give you the answer to your 3 questions but you have to go to each person in front of each line 3 times. Because you’re instantiating (moving) yourself to get their names, their ages, and finally their favorite hobby… You get the picture.

In code-r words

Not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton() {
      // Prevent instantiation outside of class    
    }
    public static Singleton Instance {
        get {
            if (instance==null) {
            instance = new Singleton();
            }
        return instance;
        }
    }
}