在.net下实现Singleton,估计很多人都知道了.下面的代码可以说经典.
class MySingleton
{
private static MySingleton instance = new MySingleton();
public static MySingleton Instance { get { return instance; } }
}
{
private static MySingleton instance = new MySingleton();
public static MySingleton Instance { get { return instance; } }
}
但是继承的Singleton模式的实现的实现似乎不多见, 也没见过什么泛式.下面这个是我目前看到最好的.
供大家参考.其实其中的思想远不止实现Singleton模式, 它提供了一种方法可以使得父类可以调用尚不存在的子类中的静态方法.
using System;
using System.Reflection;
abstract class MySingleton
{
private static MySingleton instance = null;
private static readonly object padlock = new object();
public static MySingleton GetInstance()
{
lock (padlock)
{
if (instance == null)
SetInstance(typeof(ChildSingleton));
return instance;
}
}
public static void SetInstance(MySingleton instance)
{
lock (padlock)
{
MySingleton.instance = instance;
}
}
public static void SetInstance(Type type)
{
if (type.IsSubclassOf(typeof(MySingleton)))
{
MethodInfo register = type.GetMethod("Register", BindingFlags.Public | BindingFlags.Static);
if (register == null)
throw new InvalidOperationException("Instance must have a static Register method.");
register.Invoke(null, null);
}
}
public virtual string Info { get { return this.GetType().FullName; } }
}
class ChildSingleton : MySingleton
{
private static ChildSingleton instance = new ChildSingleton();
private ChildSingleton()
{
}
public static void Register()
{
MySingleton.SetInstance(instance);
}
}
class OtherSingleton : MySingleton
{
private static OtherSingleton instance = new OtherSingleton();
private OtherSingleton()
{
}
public static void Register()
{
MySingleton.SetInstance(instance);
}
}
class EntryPoint
{
public static void Main(string[] args)
{
MySingleton singleton = MySingleton.GetInstance();
Console.WriteLine(singleton.Info);
MySingleton.SetInstance(typeof(OtherSingleton));
singleton = MySingleton.GetInstance();
Console.WriteLine(singleton.Info);
}
}