获取单个实例,而不是使用辛格尔顿什么好方法(在C#) [英] Any good way for getting a single instance instead of using Singleton (in C#)

查看:103
本文介绍了获取单个实例,而不是使用辛格尔顿什么好方法(在C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前用单获得一个实例,但它是由别人是因为在测试中有些吃亏的否认。有什么缺点?
是否有得到一个全局实例任何其他好办法?

I used to use singleton get a single instance, but it was disclaimed by others because of some disadvantage in testing. What's the disadvantage? Is there any alternative good way for getting a global instance?

因此,它是确定为我创造只有一个单例类应用作为全球中心全球?这样我可以把Global.Instance任何其他类的单一实例。

So is it OK for me to create only one singleton class Global in application as global hub? so that I can put any other class's single instances in Global.Instance.

推荐答案

好吧,为什么单身是坏的,你可以在这里阅读:什么是坏对单身

Ok, why singletons are bad you can read here: What is so bad about Singletons?

具体的测试:一个典型的Singleton模式看起来像这样

Specifically for testing: A typical singleton pattern looks like this

class MyClass
{
    private static MyClass m_Instance = new MyClass();
    public static MyClass Instance
    {
        get { return m_Instance; }
    }
}

现在想象你必须运行一大堆测试所有涉及 MyClass.Instance 。这个类随身携带的状态,你通常需要必须有一个方法来测试之间的重新设置,使每个测试可以用干净的初始状态开始。现在,您可以添加复位()方法,但是这意味着你只是为了能够测试它这是不可取的目的代码添加到您的类。

Now imagine you have to run a whole bunch of tests all involving the MyClass.Instance. This class carries around a state and you usually need to have to have a way to reset it between tests so that each test can start with a clean initial state. Now you can add a Reset() method but that means you add code to your class just for the purpose of being able to test it which is not desirable.

,而不是用什么:嗯,在本身的单身是不是真的坏事。它导致的问题是,它可以很容易地编写这样的代码:

What to use instead: Well, the singleton in itself is not really the bad thing. The problem it leads to is that it makes it easy to write code like this:

class SomeClass
{
    public void SomeMethod()
    {
        ...
        MyClass.Instance.DoSomething();
    }
}

现在你已经创建的一个实例一个隐含的依赖你不能轻易打破。解决了这个问题的一个方法是通过依赖注入(这是已经提到过):

Now you have created an implicit dependency on the singleton instance you cannot easily break. One approach which solves this problem is via dependency injection (which was already mentioned):

class SomeClass
{
    public SomeClass(MyClass myClass)
    {
        m_MyClass = myClass;
    }

    public void SomeMethod()
    {
        ...
        m_MyClass.DoSomething();
    }
}



,你可以做:

and you can do:

var someClass = new SomeClass(MyClass.Instance);

在你的程序以及

var someClass = new SomeClass(new MyClass());



进行测试。

for testing.

所以,单身人士没有那么糟糕,有时候合适工作的工具,但是你必须小心你如何使用它们。

So singletons are not that bad and sometimes the right tool for the right job, however you need to be careful of how you use them.

这篇关于获取单个实例,而不是使用辛格尔顿什么好方法(在C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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