简体   繁体   English

Singleton和其他参数化的构造函数

[英]Singleton and other parameterized constructors

I have just made my class singleton by following simple code: 我通过以下简单代码使我的班级单身人士:

public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

Now, I also want to be able to set some properties using a constructor. 现在,我还希望能够使用构造函数设置一些属性。 However, I am little worried since this is my first time with singleton. 但是,我很少担心,因为这是我第一次与Singleton在一起。 I have following questions: 我有以下问题:

  1. How can I have other parameterized constructor and also make sure that when a client application uses my class they get singleton. 我如何拥有其他参数化的构造函数,并确保当客户端应用程序使用我的类时,它们会变得单例。

  2. Would it be a bad idea to have multiple constructor with singleton class? 在单例类中有多个构造函数会是个坏主意吗?

  3. What are there are multiple calls to the new "parameterized constructor" with different values? 对具有不同值的新“参数化构造函数”有多个调用?

Singletons are stateless, should not have any state in it. 单例是无状态的,不应包含任何状态。 By looking at your problem you are looking for a Factory Pattern which can be created by Singleton. 通过查看您的问题,您正在寻找可以由Singleton创建的Factory Pattern。 I think this link will help you factory-method-and-singleton-patterns 我认为此链接将帮助您使用工厂方法和单一模式

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

相关问题 参数化单例模式 - Parameterized singleton patterns 为什么 JsonConvert 对待默认构造函数和参数化构造函数的方式不同? - Why does JsonConvert treat default constructors and parameterized constructors differently? 通过反射进行深度复制,涉及参数化构造函数 - Deep copy via reflection involving parameterized constructors 无法调试在Autofac中注册的Singleton的构造函数 - Unable to debug constructors of Singleton registered with Autofac 为什么这个 singleton 代码示例中有两个构造函数 - Why two constructors in this singleton code example 使用静态构造函数在C#中创建单例 - Using Static constructors to create a singleton in C# 从类内部解决Autofac依赖关系,而无需参数化构造函数 - Resolving Autofac dependencies from inside of classes, without parameterized constructors 使用带有类型参数的工厂方法,通过参数化构造函数创建派生类 - Create derived classes with parameterized constructors using factory method with type parameter Activator.CreateInstance - 如何创建具有参数化构造函数的类的实例 - Activator.CreateInstance - How to create instances of classes that have parameterized constructors 在其他方法中调用参数化方法 - Calling Parameterized Methods in Other Methods
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM