创建型模式(Singleton)
class MyClass
{
static MyClass c;
private MyClass()
{
}
public static MyClass GetSingleton()
{
if(c==null)
{
c=new MyClass();
}
return c;
}
}
//MyClass c1=MyClass.GetSingleton();
//MyClass c2=MyClass.GetSingleton();
{
static MyClass c;
private MyClass()
{
}
public static MyClass GetSingleton()
{
if(c==null)
{
c=new MyClass();
}
return c;
}
}
//MyClass c1=MyClass.GetSingleton();
//MyClass c2=MyClass.GetSingleton();
为了保证访问部冲突,加上lock
class MyClass
{
static MyClass c;
static object helper=new object();
private MyClass()
{
}
public static MyClass GetSingleton()
{
if(c==null)
{
lock(helper)
{
if(c==null)
{
c=new MyClass();
}
}
}
return c;
}
}
//MyClass c1=MyClass.GetSingleton();
//MyClass c2=MyClass.GetSingleton();
还可以用 c#用的静态构造器实现
class MyClass
{
public readonly static MyClass Singleton=
new MyClass();
private MyClass()
{
}
}
class MyClass
{
public readonly static MyClass Singleton;
static MyClass()
{
Singleton=new MyClass();
}
private MyClass()
{
}
}
//MyClass c1=MyClass.Singleton;
//MyClass c2=MyClass.Singleton;