本文介绍了我可以通过这种方式为所有派生的Singleton定义一个抽象类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的抽象类,每次我要创建:

This is my abstract class which must be derived each time I want to make a Singleton:

public abstract class Singleton<T> where T : Singleton<T>
{
    private static readonly Lazy<T> _instance = new Lazy<T>(() =>
    {
        var constructor = typeof(T).GetConstructor(BindingFlags.NonPublic |
            BindingFlags.Instance, null, new Type[0], null);

        return (T)constructor.Invoke(null);
    });
    public static T Instance { get { return _instance.Value; } }
    public Singleton() { }
}

因此,每次我需要遵循Singleton设计模式,我可以这样做:

So, every time I need to follow the Singleton design pattern, I can just make this:

sealed class Server : Singleton<Server>
{
    private Server() { }
    ...
}

这是完全正确的,如果不是,为什么?

Is this completely right, and, if not, why?

编辑:


  • 在派生类示例上添加了私有构造函数,并在抽象基础上调用。

编辑:


  • 重新处理类型参数初始化。

推荐答案

自我实现的单例是反模式。如果您仅实现工厂,则无需继承并将类锁定为特定形式:

Self implemented singletons are an anti-pattern. The need to inherit, and lock your classes into a specific form goes away if you just implement a factory:

public class Server {} //Not coupled to any inheritance hierarchy.

public class Factory
{
    private readonly Lazy<Server> _server = new Lazy<Server>(() => new Server());

    public Server Server { get { return _server.Value; } }
}

但是,您实际上是将工厂用作服务定位器,并且服务定位器也被认为是一种反模式,因为您可以轻松地使用DI将Server实例注入到您的使用类中。

However, you're really using the factory as a service locator and service locator is also considered an anti-pattern as you can easily just use DI to inject the Server instance into your consuming classes.

public class MyServerConsumer
{
    public MyServerConsumer(Server server)
    {
      //Do stuff.      
    }
}

温莎风格注册:

 ... 
 Component.For<Server>();
 ...

请注意,从未提及单例这个词吗?您仍然可以获得一个对象的单个实例,但是不必编写代码来维持这种关系,并且您的类从一开始就不受单一概念的约束和破坏。

Notice that the word singleton is never mentioned? You still get 'a single instance of an object', but you don't have to write code to maintain that relationship, and your classes are not constrained and corrupted by the concept of 'singleton' from the start

这篇关于我可以通过这种方式为所有派生的Singleton定义一个抽象类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:39