C# Singleton implement

 1// Singleton
 2using System;
 3
 4public class Singleton
 5{
 6   private static Singleton instance;
 7
 8   private Singleton() {}
 9
10   public static Singleton Instance
11   {
12      get 
13      {
14         if (instance == null)
15         {
16            instance = new Singleton();
17         }

18         return instance;
19      }

20   }

21}

22
23

 1//Static Initialization
 2public sealed class Singleton
 3{
 4   private static readonly Singleton instance = new Singleton();
 5   
 6   private Singleton(){}
 7
 8   public static Singleton Instance
 9   {
10      get 
11      {
12         return instance; 
13      }

14   }

15}

16
17

 1//Multithreaded Singleton
 2using System;
 3
 4public sealed class Singleton
 5{
 6   private static volatile Singleton instance;
 7   private static object syncRoot = new Object();
 8
 9   private Singleton() {}
10
11   public static Singleton Instance
12   {
13      get 
14      {
15         if (instance == null
16         {
17            lock (syncRoot) 
18            {
19               if (instance == null
20                  instance = new Singleton();
21            }

22         }

23
24         return instance;
25      }

26   }

27}

28
posted @ 2005-09-08 13:36  Rookie.Zhang  阅读(215)  评论(0编辑  收藏  举报