C# 单例3种写法
2015-08-27 13:56
232 查看
public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
lock(lockHelper)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
第三种可能是C#这样的高级语言特有的,实在懒得出奇
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
哦,shit!
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
lock(lockHelper)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
第三种可能是C#这样的高级语言特有的,实在懒得出奇
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
哦,shit!
相关文章推荐
- c#中各种进制之间转换
- 【c#】关于终止以及删除主进程创建的线程以及进程的方法
- c#中ToString()格式化数据
- C#编程获取资源文件中图片的方法
- C#动态创建button的方法
- c# 服务程序重启自身
- C# PPT 为形状设置三维效果
- C#中图片与BASE64码互相转换
- C#动态调用WCF接口
- c# 右下角弹窗提示
- C#生成音频文件以及转换成需要的格式
- C# PPT 为形状设置三维效果
- C#通过反射获取上层调用方法信息
- C# TreeView+checkBox 自动加载
- c# winform datagridview 编辑单元格内容,没有保存编辑内容
- C# WPF回显
- C#:序列化值与解码二进制
- C# Dev控件中的 PropertyGridControl 属性控件的基本用法以及排序
- C# 获取指定目录下所有文件信息、删除文件、目录,移动目录,拷贝目录
- Search for a Range C#