单例实现方式

游戏中很多地方,都需要用到单例模式,虽然单例实现代码不多,但是每一个脚本都重复写的话,也相当的麻烦。

我们可以这样,写一个泛型的父类,来实现这个单例模式,然后其余的只要继承这个父类,自然就有 1 public class HNSingleton<T> where T :class

 2     {
 3 
 4         #region 私有变量
 5 
 6         private static T g_instance;                                                // 静态实例句柄
 7         private static readonly object g_instanceLock = new object();               // 锁,控制多线程冲突
 8 
 9         #endregion
10 
11         #region 公开属性
12 
13         /// <summary>
14         /// 获取单例
15         /// </summary>
16         /// <remarks>即单例模式中所谓的全局唯一公共访问点</remarks>
17         public static T Instance
18         {
19             get
20             {
21                 // 此处双重检测,确保多线程无冲突
22                 if (g_instance == null)
23                 {
24                     lock (g_instanceLock)
25                     {
26                         if (g_instance == null)
27                         {
28                             g_instance = (T)System.Activator.CreateInstance(typeof(T), true);
29                             System.Console.WriteLine("hnu3d.........unity......create instance:" + g_instance.ToString());
30 
31                         }
32                     }
33                 }
34 
35             
36 
37                 return g_instance;
38             }
39         }
40 
41 
42 
43         #endregion
44 
45 
46 
47         #region 销毁对象
48 
49         public void DelMe()
50         {
51             // 此处双重检测,确保多线程无冲突
52             if (g_instance != null)
53             {
54                 lock (g_instanceLock)
55                 {
56                     if (g_instance != null)
57                     {                  
58                         HNLogger.Log ("..delet---:" + g_instance.ToString());
59                         g_instance = null;
60                     }
61                 }
62             }
63 
64         }
65 
66         
68     }

当其它脚本需要单例模式时,只需要继承该脚本即可实现单例模式了。

posted @ 2017-03-25 14:18  gameDesigner  阅读(146)  评论(0编辑  收藏  举报