C#设计模式——单例模式

来源:互联网 发布:mac 风暴英雄 鼠标 编辑:程序博客网 时间:2024/06/06 00:18

说明:

  • 单例模式——在整个进程中,只被实例化一次
  • 单例模式的好处——只允许创建一个对象,因此节省内存,加快访问对象的速度
  • 单例模式的坏处——如果同一个单例在不同的用例场景中发生变化,就会出现数据错误,也就是不适用与变化的对象。

常见的单例写法:

单线程环境下:
/// <summary>/// 适用于单线程情况下,在Unity这类引擎中满足使用/// </summary>public class Singleton{    static Singleton instance = null;    public static Singleton Instance    {        get        {            if (instance == null)            {                instance = new Singleton();            }            return instance;        }    }}


在多线程环境下:
/// <summary>/// 适用于多线程情况下,确保线程安全/// </summary>public class Singleton{    static Singleton instance = null;    static Object lockObj = new Object();    public static Singleton Instance    {        get        {            if (instance == null)            {                lock (lockObj)                {                    if (instance == null)                    {                        instance = new Singleton();                    }                }            }            return instance;        }    }}

静态初始化:
/// <summary>/// 静态构造方法:CLR运行时,第一次使用这个类之前,会而且只会执行一次/// </summary>public class Singleton{    static Singleton instance = null;    static Singleton()    {        instance = new Singleton();    }    public static Singleton Instance    {        get        {            return instance;        }    }}

泛型单例:
public class single<T>where T:new (){     private static T singleClass;    public static T Instance    {        get        {            if (singleClass == null)            {                singleClass =new T();            }            return singleClass;        }    }}




0 0
原创粉丝点击