设计模式-单例模式

 

设计模式,是我们写出优质代码的基础,对于代码的重构以及后期的维护都至关重要。

单例模式是最简单的设计模式之一,他适用于对某些类要求只有一个实例时,有点像静态类的感觉。

用实例简单介绍一下:

创建单例实体类:SingleInstance.cs

View Code
 1 public class SingleInstance
 2     {
 3         //全局唯一的实例
 4         private static SingleInstance instance;
 5 
 6         //同步对象锁
 7         private static object syncLock = new object();
 8 
 9         //保护级别的构造函数
10         protected SingleInstance()
11         {
12         }
13 
14         //对外公开访问唯一实例的方法
15         public static SingleInstance GetInstance()
16         {
17             //支持多线程应用程序通过
18             //“双重检查锁定”模式,(一旦实例存在)避免锁定每次调用这个方法
19             if (instance == null)
20             {
21                 lock (syncLock)
22                 {
23                     if (instance == null)
24                     {
25                         instance = new SingleInstance();
26                     }
27                 }
28             }
29 
30             return instance;
31         }
32 
33         public int Num
34         {
35             get;
36             set;
37         }
38     }

测试单例的效果:Program.cs

View Code
 1  static void Main(string[] args)
 2         {
 3             SingleInstance s1 = SingleInstance.GetInstance();
 4             SingleInstance s2 = SingleInstance.GetInstance();
 5 
 6             s1.Num = 10;
 7             s2.Num = 20;
 8             s1.Num = 123456;
 9             Console.WriteLine(s1.Num);
10             Console.WriteLine(s2.Num);
11             Console.WriteLine("s1和s2是同一个对象吗?" + (s1 == s2).ToString());
12             Console.Read();
13 
14         }

运行结果:

希望大家动手敲一下代码,加深印象。

 

posted @ 2012-11-09 10:38  xiaobudian8493  阅读(163)  评论(2编辑  收藏  举报