C#单例模式
public class Singleton
{
//定义一个全局私有变量
private static Singleton _singletomn;
private static int iCount;
//定义一个只读的静态对象,为类创建时创建
private static readonly object _lockObj = new object();
/// <summary>
/// 构造函数为内部的,外部不可实例化
/// </summary>
private Singleton() {}
public static int Count {
get { return iCount; }
}
/// <summary>
/// 定义一个全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance() {
iCount ++;
//保证只能实例化一次
if (_singletomn == null)
{
lock (_lockObj)
{
if (_singletomn==null)
{
_singletomn = new Singleton();
}
}
}
return _singletomn;
}
}
{
//定义一个全局私有变量
private static Singleton _singletomn;
private static int iCount;
//定义一个只读的静态对象,为类创建时创建
private static readonly object _lockObj = new object();
/// <summary>
/// 构造函数为内部的,外部不可实例化
/// </summary>
private Singleton() {}
public static int Count {
get { return iCount; }
}
/// <summary>
/// 定义一个全局访问点
/// </summary>
/// <returns></returns>
public static Singleton GetInstance() {
iCount ++;
//保证只能实例化一次
if (_singletomn == null)
{
lock (_lockObj)
{
if (_singletomn==null)
{
_singletomn = new Singleton();
}
}
}
return _singletomn;
}
}
class Program
{
static void Main(string[] args)
{
Console.Write(Singleton.Count);
Console.ReadKey();
}
}
{
static void Main(string[] args)
{
Console.Write(Singleton.Count);
Console.ReadKey();
}
}