单键模式有三个特点:1.单键类只能有一个实例。
2.单键类必须自己创建自己的唯一实例。
3.单键类必须给所有其他对象提供这一实例。
using
System;
class Singleton
... {
private static Singleton instance;
protected Singleton()
...{
}
public static Singleton Instance()
...{
if(instance==null)
...{
instance=new Singleton();
}
return instance;
}
}
public class Client
... {
public static void Main()
...{
Singleton s1=Singleton.Instance();
Singleton s2=Singleton.Instance();
if (s1==s2)
...{
Console.WriteLine("The same instance.");
}
}
}
class Singleton
... {
private static Singleton instance;
protected Singleton()
...{
}
public static Singleton Instance()
...{
if(instance==null)
...{
instance=new Singleton();
}
return instance;
}
}
public class Client
... {
public static void Main()
...{
Singleton s1=Singleton.Instance();
Singleton s2=Singleton.Instance();
if (s1==s2)
...{
Console.WriteLine("The same instance.");
}
}
}