在C#中实现单例可继承类 [英] Implementing singleton inheritable class in C#

查看:688
本文介绍了在C#中实现单例可继承类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在C#中,您可以实现Singleton类,如下所示:

I found that in C# you can implement a Singleton class, as follows:

class Singleton
{

    private static Singleton _instance;

    public static Singleton Instance
    {
        get { return _instance ?? (_instance = new Singleton()); }
    }

    protected Singleton() { }
}

适用于Singleton类型的实例,即:

Which works for instances of type Singleton, i.e:

var a = Singleton.Instance;
var b = Singleton.Instance;
Console.WriteLine(ReferenceEquals(a, b)); //Prints True.

但是如果我希望Singleton的派生类也遵循Singleton模式,即:

But what if I want that derived classes of Singleton also follow the Singleton pattern, i.e:

class A:Singleton
{ ... }
A a = A.Instance;

在这种情况下,Singleton类可以访问静态成员Instance并创建一个Singleton实例,这不是目标. 此外,此解决方案还有两个主要问题:

In this case the static member Instance is accessed by Singleton class and creates a Singleton instance, which isn't the objective. Besides, there are two main problems with this solution:

  • 派生类可以实现自己的构造函数,并且不会丢失Singleton模式.
  • 如果还有Singleton的另一个实例,则派生类将引用该较少派生的实例
  • The derived class can implement its own constructor and lose the Singleton Pattern.
  • If there is another instance of Singleton then the derived class is going to reference that less-derived instance

我的问题是:还有另一种方法可以在C#中实现Singleton类,以确保派生类也是singleton吗?

My question is: Is there another way to implement a Singleton class in C# ensuring that derived class are also singleton?

推荐答案

忽略通常的不要使用Singleton,请看一下您的设计."参数,可以想象这样实现一个参数(假设您的派生类具有默认构造函数):

Ignoring the usual "Don't use a Singleton, look at your design." arguments, you could conceivably implement one as thusly (assuming your derived classes have default constructors):

public abstract class Singleton<T> where T : class, new()
{
    private static T _instance;

    public static T GetInstance()
    {
        if(_instance == null)
            _instance = new T();
        return _instance;
    }
}

并这样导出:

public class SingletonA : Singleton<SingletonA> { /* .... */ }
public class SingletonB : Singleton<SingletonB> { /* .... */ }

但是,我个人并不真正提倡这种单例方法.它们确实有其(很少)用途,但事实证明,使用流浪汉更为痛苦-转向荣耀的全局变量容器.

But, I really don't advocate this singleton approach personally. They do have their (rare) uses, but they can turn out to be more of a pain in the bum - turning in to glorified global variable containers.

此外,请注意线程安全性.

Also, be mindful of thread-safety.

这篇关于在C#中实现单例可继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆