如何抽象一个单例类



我就是这样写我的单例类的

public class MyClass
{
    /// <summary>
    /// Singleton
    /// </summary>
    private static MyClass instance;
    /// <summary>
    /// Singleton access.
    /// </summary>
    public static MyClass Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MyClass();
            }
            return _instance;
        }
    }
    private MyClass() { .... }
}

如何创建可重用的单例模式?

单例模式提出了以下挑战。

  • 构造器为privateprotected
  • 基类不能实例化继承的类。所以你可以重用一个共同的抽象MyAbstractSingletonClass
  • 必须有一个本地只读属性来获取实例。

我在许多类上使用这种模式,并且总是必须编写相同的代码。当我需要一个单例时,我该如何编写可重用的东西?

您可以使用自引用泛型类型约束和"new()"类型约束的组合来实现这一点。

"新"约束确保任何子类将始终有一个无参数的构造函数,所以_instance = new T();将始终工作。

自引用类型约束确保"Instance"静态属性总是返回正确的type;不是"基础"类型。你的单例基类看起来像这样:

public abstract class SingletonBase<T> 
    where T : SingletonBase<T>, new()
{
    private static T _instance = new T();
    public static T Instance
    {
        get
        {                
            return _instance;
        }   
    }
}

你的子类看起来像这样:

public class MyChildSingleton : SingletonBase<MyChildSingleton>
{
    //Done!
}

当然,如果你希望你的单例是通用的,你也应该稍微改变你的"创建单例实例"代码,使用"双重检查锁"模式,或者Lazy类,使它线程安全。

一个重要的警告:如果你使用这个方法,"new()"约束几乎可以确保你的类总是有一个公共的、无参数的构造函数。这意味着如果最终用户真的想调用new MyChildSingleton(),就可以完全绕过你的单例实例。您的单例模式将"按惯例"执行,而不是严格执行。要解决这个问题需要更多的工程技术。在上面的场景中,约定似乎是你应该将静态实例命名为"Default"而不是"Instance",这巧妙地传达了这样一个事实:你的类提供了一个"建议的"单例实例,但使用它在技术上是可选的。

我已经做了一些尝试来严格执行单例模式,最终的结果是使用反射来手动调用私有构造函数。您可以在这里看到我的完整代码尝试

真正的解决方案是从BTownTKD的方法开始,但使用Activator对其进行扩展。方法,允许子类保留私有构造函数。

父类

public abstract class SingletonBase<T> where T : SingletonBase<T>
{
    private static readonly Lazy<T> Lazy =
        new(() => (Activator.CreateInstance(typeof(T), true) as T)!);
    public static T Instance => Lazy.Value;
}

子类

public sealed class MySingleton : SingletonBase<MySingleton>
{
    private MySingleton() { }
}

完整实现示例

添加到BTownTKD的答案中,在运行时限制构造函数调用实际上非常简单(不确定编译时是否可能)。你所要做的就是在SingletonBase中添加一个受保护的构造函数,如果_instance不为空,就会抛出异常。即使构造函数是从外部调用的第一个对象,也会抛出异常。

我设法在单例基础上应用这种技术,并使其变得懒惰和线程安全,如下所述:http://csharpindepth.com/Articles/General/Singleton.aspx

结果(附用法说明):

/// <summary>
/// Generic singleton class, providing the Instance property, and preventing manual construction.
/// Designed as a base for inheritance trees of lazy, thread-safe, singleton classes.
/// Usage:
/// 1. Sub-class must use itself, or its sub-class, as the type parameter S.
/// 2. Sub-class must have a public default constructor (or no constructors).
/// 3. Sub-class might be abstract, which requires it to be generic and demand the generic type
///    have a default constructor. Its sub-classes must answer all these requirements as well.
/// 4. The instance is accessed by the Instance getter. Using a constructor causes an exception.
/// 5. Accessing the Instance property in an inner initialization in a sub-class constructor
///    might cause an exception is some environments.
/// </summary>
/// <typeparam name="S">Lowest sub-class type.</typeparam>
public abstract class Singleton<S> where S : Singleton<S>, new()
{
    private static bool IsInstanceCreated = false;
    private static readonly Lazy<S> LazyInstance = new Lazy<S>(() =>
        {
            S instance = new S();
            IsInstanceCreated = true;
            return instance;
        });
    protected Singleton()
    {
        if (IsInstanceCreated)
        {
            throw new InvalidOperationException("Constructing a " + typeof(S).Name +
                " manually is not allowed, use the Instance property.");
        }
    }
    public static S Instance
    {
        get
        {
            return LazyInstance.Value;
        }
    }
}

我必须说我没有做过密集的多线程测试,但是正如一些人已经说过的,您总是可以使用旧的双重检查技巧。

在基类中实现单例模式是有问题的。

但是,您可以实现其他可能适合您尝试完成的创建设计模式。例如,看一下抽象工厂

你是正确的-就目前而言,你无法做到这一点。但是您可以使用泛型来处理它,注意,使用这种方法,您将为每个惟一派生类型:

获得一个单例实例。
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = new MyDerivedClass();
            Console.WriteLine(x.ToString());
            Console.WriteLine(x.Instance.ToString());
            Console.ReadKey();
        }
    }

    public abstract class MyBaseClass<T> where T : class, new()
    {
        protected T GetInstance()
        {
            if (_instance == null)
            {
                lock (_lockObj)
                {
                    if (_instance == null)
                        _instance = new T();
                }
            }
            return _instance;
        }
        public T Instance
        {
            get { return GetInstance(); }
        }
        private volatile static T _instance;
        private object _lockObj = new object();
    }
    public class MyDerivedClass : MyBaseClass<MyDerivedClass>
    {
        public MyDerivedClass() { }
    }
}

我相信使用@Buvy的解决方案,您将获得每个线程一个实例,这可能是他想要的。你必须稍微修改一下,才能在多个线程中获得一个实例。

public abstract class BaseSingleton<T> 
    where T : BaseSingleton<T>
{
    private static readonly Lazy<T> lazy =
                    new Lazy<T>(() => Activator.CreateInstance(typeof(T), true) as T);
    public static T Instance { get { return lazy.Value; } }
}

我最近对一个相关问题给出了这样的答案:

https://stackoverflow.com/a/20599467

使用此方法,基类管理派生类的所有实例的创建,因为所有派生类构造函数都需要只有基类才能提供的对象,并且不需要无参数构造函数的限制。

我建议的例子:

基类

public abstract class SingletonBase<T> where T : class
{
  private static readonly Lazy<T> sInstance = new Lazy<T>(() => CreateInstanceOfT());
  public static T Instance { get { return sInstance.Value; } }
  private static T CreateInstanceOfT()
  {
    return Activator.CreateInstance(typeof(T), true) as T;
  }
}
使用

public class yourClass : SingletonBase<yourClass>
{
   public yourMethod()
   {
   }
}

这样使用你的单例类:

yourClass.Instance.yourMethod();

更多信息参见我的答案来源在这个链接

最新更新