设计模式之单例模式

单例模式是使用频率最高的一种模式,并且本人认为也是最简单的模式之一,主要是为了保证在程序允许过程中只有一个实例。类图如下:

单例模式为了避免在外部创建实例,构造方法会定义为Private.。

代码如下:

 1     class Singleton
 2     {
 3         private static Singleton _instance;
 4         private Singleton()
 5         { }
 6         public static Singleton GetInstance()
 7         {
 8             if (_instance == null)
 9                 _instance = new Singleton();
10             return _instance;
11         }
12     }
Singleton

需要注意的事,GetInstance方法里创建实例要注意线程安全。

最好的方法是写成如下形式:

 1     class Singleton
 2     {
 3         private static Singleton _instance=new Singleton();
 4         private Singleton()
 5         { }
 6         public static Singleton GetInstance()
 7         {
 8             return _instance;
 9         }
10     }
Singleton

客户端代码:

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             var instance1 = Singleton.GetInstance();
 6             var instance2 = Singleton.GetInstance();
 7             Console.WriteLine("Instance1 和 Instance2 是不是同一个实例:{0}", instance1.Equals(instance2));
 8             Console.ReadKey();
 9         }
10     }
Program

运行效果如下:

posted on 2015-06-06 20:36  Jason-Han  阅读(99)  评论(0)    收藏  举报

导航