// 不要用这种方式
public sealed class Singleton
{
private static Singleton instance=null;//声明自己本身的静态实例
private Singleton(){}//私有构造
public static Singleton Instance() //提供全局访问点
{
if (instance==null)//实例不存在则创建
{
instance = new Singleton();
}
return instance;
}
}
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();//定义一个标识确保线程同步
Singleton(){}
public static Singleton Instance()
{
lock (padlock)//线程到达时加锁 运行完之后解锁 当遇到加锁线程就会挂起等待解锁
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton(){}
public static Singleton Instance
{
get
{
if (instance == null)//外层的if语句块,这使得每个线程欲获取实例时不必每次都得加锁,因为只有实例为空时(即需要创建一个实例),才需加锁创建
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// 显示的static 构造函数
//静态构造函数抑制了beforefieldinit 特性(访问成员之前就执行静态函数)
static Singleton(){}
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
public sealed class Singleton
{
private Singleton(){}
public static Singleton Instance { get { return Nested.instance; }}
//嵌套类
private class Nested
{
//抑制beforefieldinit特性
static Nested(){}
internal static readonly Singleton instance = new Singleton();
}
}
public sealed class Singleton
{
//使用.NET4 Lazy<T>
private static readonly Lazy<Singleton> lazy =new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton() {}
}
public sealed class Singleton
{
private static readonly Singleton instance=new Singleton();//直接实例化
private Singleton(){}
public static Singleton Instance()
{
return instance;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有