C#/.NET 单例模式——懒汉式,饿汉式,三种实现方法

版权声明:本文为博主原创文章,欢迎各位转载,但须注明出处 https://blog.csdn.net/qq_34202873/article/details/85760434

C# 单例模式 ——懒汉式,饿汉式#

注释:

/// 单例模式
/// 
/// 饿汉式 :第一时间创建实例,类加载就马上创建
/// 懒汉式 :需要才创建实例,延迟加载
/// 
/// 单例模式会长期持有一个对象,不会释放
/// 普通实例使用完后释放
/// 
/// 单例可以只构造一次,提升性能(如果构造函数耗性能)
/// 
/// 单例就是保证类型只有一个实例:计数器/数据库连接池
/// 
/// 程序中某个对象,只有一个实例

懒汉式

//构造函数私有化,避免外部构建
private Singleton()//private  避免外部创建
{

}

//volatile 可以保证运行过程中值不会被重复修改
private static volatile Singleton _Singleton = null;
private static object Singleton_Lock = new object();

public static Singleton CreateInstance()
{
    if (_Singleton == null)//保证对象初始化之后,不在去等待锁
    {
        lock (Singleton_Lock)//保证只有一个线程进去
        {
            if (_Singleton == null)//保证只被实例化一次
                _Singleton = new Singleton();
        }
    }
    return _Singleton;
}//懒汉式  调用了方法才去构造

饿汉式——使用静态构造函数

/// <summary>
/// 构造函数耗时耗资源
/// </summary>
private SingletonSecond()
{

}

/// <summary>
/// 静态构造函数:由CLR保证,程序第一次使用这个类型前被调用,且只调用一次
/// 
/// 写日志功能的文件夹检测
/// XML配置文件
/// </summary>
static SingletonSecond()
{
    _SingletonSecond = new SingletonSecond();
}


private static SingletonSecond _SingletonSecond = null;
public static SingletonSecond CreateInstance()
{
    return _SingletonSecond;
}//饿汉式  只要使用类就会被构造

饿汉式——使用静态字段

private SingletonThird()
{

}

/// <summary>
/// 静态字段:在第一次使用这个类之前,由CLR保证,初始化且只初始化一次
/// </summary>
private static SingletonThird _SingletonThird = new SingletonThird();//打印个日志
public static SingletonThird CreateInstance()
{
    return _SingletonThird;
}//饿汉式  只要使用类就会被构造

猜你喜欢

转载自blog.csdn.net/qq_34202873/article/details/85760434