Home
Manage Your Code
Snippet: Singleton Pattern (C#)
Title: Singleton Pattern Language: C#
Description: Ensure a class has only one instance and provide a global point of access to it. Views: 560
Author: Michael Gage Date Added: 3/1/2007
Copy Code  
1  class Singleton
2  {
3    private static Singleton instance;
4
5    // Note: Constructor is 'protected' 
6    protected Singleton() 
7    {
8    }
9
10    public static Singleton Instance()
11    {
12      // Use 'Lazy initialization' 
13      if (instance == null)
14      {
15        instance = new Singleton();
16      }
17
18      return instance;
19    }
20  }
21
Usage
    public static LoadBalancer GetLoadBalancer()
    {
      // Support multithreaded applications through 
      // 'Double checked locking' pattern which (once 
      // the instance exists) avoids locking each 
      // time the method is invoked 
      if (instance == null)
      {
        lock (syncLock)
        {
          if (instance == null)
          {
            instance = new LoadBalancer();
          }
        }
      }

      return instance;
    }