Overview Of Singleton Pattern

Definition

The singleton is a class that has only one instance and provides a global point of access to it.

Concept

A particular class should have only one instance. You can use this instance whenever you need it and therefore avoid creating unnecessary objects.

Real-Life Example

Suppose you are a member of a sports team and your team is participating in a tournament. When your team plays against another team, as per the rules of the game, the captains of the two sides must have a coin toss. If your team does not have a captain, you need to elect someone to be the captain first. Your team must have one and only one captain.

Computer World Example

In some software systems, you may decide to maintain only one file system so that you can use it for the centralized management of resources.

Example
  1. using System;  
  2. namespace SingletonPatternEx {  
  3.     public sealed class Singleton {  
  4.         private static readonly Singleton instance = new Singleton();  
  5.         private int numberOfInstances = 0;  
  6.         //Private constructor is used to prevent    
  7.         //creation of instances with 'new' keyword outside this class    
  8.         private Singleton() {  
  9.             Console.WriteLine("Instantiating inside the private constructor.");  
  10.             numberOfInstances++;  
  11.             Console.WriteLine("Number of instances ={0}", numberOfInstances);  
  12.         }  
  13.         public static Singleton Instance {  
  14.             get {  
  15.                 Console.WriteLine("We already have an instance now.Use it.");  
  16.                 Chapter 1 Singleton Pattern  
  17.                 9  
  18.                 return instance;  
  19.             }  
  20.         }  
  21.     }  
  22.     class Program {  
  23.         static void Main(string[] args) {  
  24.             Console.WriteLine("***Singleton Pattern Demo***\n");  
  25.             //Console.WriteLine(Singleton.MyInt);    
  26.             // Private Constructor.So,we cannot use 'new' keyword.    
  27.             Console.WriteLine("Trying to create instance s1.");  
  28.             Singleton s1 = Singleton.Instance;  
  29.             Console.WriteLine("Trying to create instance s2.");  
  30.             Singleton s2 = Singleton.Instance;  
  31.             if (s1 == s2) {  
  32.                 Console.WriteLine("Only one instance exists.");  
  33.             } else {  
  34.                 Console.WriteLine("Different instances exist.");  
  35.             }  
  36.             Console.Read();  
  37.         }  
  38.     }  
  39. }