保证一个类仅有一个实例,并提供一个该实例的全局访问点。
//不能完全支持多线程
public class Singleton
{
private static Singleton singleton;
int x;
private Singleton(int x)
{
this.x = x;
}
public static Singleton GetSingleton(int x)
{
if(singleton == null)
{
//在if之后与本句之前可能线程不安全
singleton = new Singleton(x);
}
return(singleton);
}
public string GetValue()
{
++x;
return(x.ToString());
}
}
//支持多线程
public class Singleton
{
//volatile的设置使C#不允许做代码调整,以使程序完全支持多线程
private static volatile Singleton singleton;
private static object lockHelper = new object();
int x;
private Singleton(int x)
{
this.x = x;
}
public static Singleton GetSingleton(int x)
{
if(singleton == null)
{
lock(lockHelper)
{
if(singleton == null)
{
singleton = new Singleton(x);
}
}
}
return(singleton);
}
public string GetValue()
{
++x;
return(x.ToString());
}
}
//支持多线程
public class Singleton
{
public static readonly Singleton singleton = new Singleton();
int x;
private Singleton()
{
x = 0;
}
public int X
{
get
{
return(this.x);
}
set
{
this.x = value;
}
}
public string GetValue()
{
++x;
return(x.ToString());
}
}