简体   繁体   English

C#Singleton模式

[英]C# Singleton Pattern

I use the singleton pattern in a lot of places, sometimes the constructor does nothing, other times it's initialising things. 我在很多地方使用单例模式,有时候构造函数什么都不做,有时候它会初始化。 I wondered if there was a way to set up an abstract class to minimise my code repetition a bit, ie I don't need public static readonly Singleton _Instance = new Singleton(); 我想知道是否有办法设置一个抽象类来最小化我的代码重复,即我不需要public static readonly Singleton _Instance = new Singleton(); in every single class, just one base class. 在每一个类中,只有一个基类。 I understand interfaces are not an option. 我理解接口不是一种选择。

I've tried using the following (taken from here ); 我尝试过使用以下内容(取自此处 );

public abstract class Singleton<T> where T : new()
{
    static Singleton()
    {
    }

    private static readonly T _Instance = new T();

    public static T Instance
    {
        get { return _Instance; }
    }
}

The problem with this is that I can't override the constructor for the cases where I need to initialise things. 这个问题是我不能覆盖我需要初始化的情况的构造函数。 Is what I'm trying to do even possible? 我正在努力做甚么可能吗? Or should I just keep doing what I'm doing and not worry about a base singleton class? 或者我应该继续做我正在做的事情,而不是担心基础单身人士课程?

I wondered if there was a way to set up an abstract class to minimise my code repetition a bit 我想知道是否有办法设置一个抽象类来最小化我的代码重复

No, there isn't. 不,没有。 As soon as you've got an abstract class, you've got a class which can be instantiated multiple times. 一旦你有了一个抽象类,你就有了一个可以多次实例化的类。 I've seen various people try to do something like this, but the end result is either not a singleton or is more complicated than just doing what you're already doing. 我已经看到不同的人试图做这样的事情,但最终的结果要么不是单身,要么比做你已经做的更复杂。

Is what I'm trying to do even possible? 我正在努力做甚么可能吗? Or should I just keep doing what I'm doing and not worry about a base singleton class? 或者我应该继续做我正在做的事情,而不是担心基础单身人士课程?

You shouldn't try to create a base singleton class - but if I were you I'd try to stop using quite so many singletons in the first place. 你不应该尝试创建一个基础单例类 - 但如果我是你,我会尝试首先停止使用这么多的单身人士。 The singleton pattern is very easily overused, and it's tantamount to an anti-pattern. 单例模式很容易被过度使用,这无异于反模式。 See if you can refactor towards dependency injection, using a configuration which happens to create only one instance of each of these classes, but where that's a matter of configuration rather than enforced by the class itself. 看看你是否可以重构依赖注入,使用恰好只创建每个类的一个实例的配置,但这是配置问题而不是类本身强制执行。

Aside from anything else, unit testing involving singletons tends to be a pain, simply because it's global state which needs cleaning up between tests etc. 除了其他任何事情,涉及单身人士的单元测试往往是一种痛苦,仅仅因为它是需要在测试之间进行清理的全局状态等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM