单例类只能有一个实例,单例类必须自己创建自己的唯一实例,单例类必须给所有其他对象提供这一事例。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
class Singleton
{
/// <summary>
/// 私有的类对象
/// </summary>
private static Singleton instance;
{
class Singleton
{
/// <summary>
/// 私有的类对象
/// </summary>
private static Singleton instance;
protected Singleton() { }
public static Singleton Instance()
{
if (instance == null)
instance = new Singleton();
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
}
public class Client
{
public static void Main()
{
Singleton s1 = Singleton.Instance();
{
public static void Main()
{
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
Console.WriteLine("The same instance");
}
}
}
Console.WriteLine("The same instance");
}
}
}
写法二:
sealed class Singleton
{
private Singleton();
public static readonly Singleton Instance=new Singleton();
}
Singleton类被声明为sealed,以此保证它自己不会被继承,将原来的Instance()方法变成public readonly,并在声明时被初始化,于是在初始化Instance属性的同时Singleton类实例得以创建和装载,而私有的构造函数和readonly()保证了Singleton不会被再次实例化。
但是该方式的缺点,无法实现延迟初始化。
写法三:
public sealed class Singleton
{
Singleton(){}
public static Singleton GetInstance()
{
return Nested.instance;
}
class Nested
{
static Nested()
{}
internal static readonly Singleton instance=new Singleton();
}
}