C#中三种Singleton的实现方法
2011-12-31 15:57
267 查看
这个模式好像经常有人拿来谈论,我觉得理论意义比实际意义要大,所以列出三种写法,看着玩儿吧.
1. 普通写法
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
优点有 1. 可以扩展, 继承个子类之类的. 2. 在需要的时候才会实例化对象. 缺点就是不是线程安全.
2. 简便写法
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
} 这种最简单直接了, 并且这也是访问的时候才会实例化. 要说劣势,那就是只能用默认的构造函数,不能加什么其他的操作.
3. 普遍实现方式
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
volatile 关键字很重要,多线程时候, 使用这个变量时候会重新得到实际的内存变量,就不会访问缓存中的数值.
1. 普通写法
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
优点有 1. 可以扩展, 继承个子类之类的. 2. 在需要的时候才会实例化对象. 缺点就是不是线程安全.
2. 简便写法
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
} 这种最简单直接了, 并且这也是访问的时候才会实例化. 要说劣势,那就是只能用默认的构造函数,不能加什么其他的操作.
3. 普遍实现方式
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
volatile 关键字很重要,多线程时候, 使用这个变量时候会重新得到实际的内存变量,就不会访问缓存中的数值.
相关文章推荐
- C# 获取当前星期几三种实现方法(转)
- C#中实现Fluent Interface的三种方法
- C#三种模拟自动登录和提交POST信息的实现方法
- C#三种模拟自动登录和提交POST信息的实现方法
- C#使用DataSet Datatable更新数据库的三种实现方法
- C# winform程序实现分页的三种方法
- C#使用DataSet Datatable更新数据库的三种实现方法
- C#三种模拟自动登录和提交POST信息的实现方法[收藏]
- C#三种模拟自动登录和提交POST信息的实现方法
- C#CreateGraphics方法的三种实现方式
- C# 获取当前星期几三种实现方法
- C#实现发送邮件的三种方法
- C#实现的三种模拟自动登录和提交POST信息的方法
- C#三种模拟自动登录和提交POST信息的实现方法
- C#实现单件模式的三种常用方法
- C#三种模拟自动登录和提交POST信息的实现方法[收藏]
- C#实现的三种模拟自动登录和提交POST信息的方法
- C#实现的三种模拟自动登录和提交POST信息的方法
- 比较C#三种方法实现读取Execl数据到数据库
- C#三种模拟自动登录和提交POST信息的实现方法