通用单例 T [英] Generic Singleton<T>

查看:24
本文介绍了通用单例 T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,这是制作通用单例的正确方法吗?

I have a question, is this the correct approach to make a Generic Singleton?

 public class Singleton<T> where T : class, new()
    {
        private static T instance = null;

        private Singleton() { }

        public static T Instancia
        {
            get 
            {
                if (instance == null)
                    instance = new T();
                return instance;
            }
        }
    }

检查一些 PDF 我发现一个通用的单例是用其他方式制作的,这个其他的正确吗?

Checking some PDFs I found a generic Singleton made this other way, is this other correct?

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

    class SingletonCreator
    {
        static SingletonCreator() { }
        // Private object instantiated with private constructor
        internal static readonly T instance = new T();
    }

    public static T UniqueInstance
    {
        get { return SingletonCreator.instance; }
    }
}

推荐答案

泛型单例工厂的问题在于,由于它是泛型的,您无法控制实例化的单例"类型,因此您永远无法保证实例您创建的将是应用程序中的唯一实例.

The problem with a generic singleton factory is that since it is generic you do not control the "singleton" type that is instantiated so you can never guarantee that the instance you create will be the only instance in the application.

如果用户可以提供一个类型作为泛型类型参数,那么他们也可以创建该类型的实例.换句话说,你不能创建一个通用的单例工厂——它破坏了模式本身.

If a user can provide a type to as a generic type argument then they can also create instances of that type. In other words, you cannot create a generic singleton factory - it undermines the pattern itself.

这篇关于通用单例 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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