2

可能重复:
如何在不使用静态/全局变量的情况下实现单例?可能的?

大多数人说 Singleton 是邪恶的原因之一是它提供了一个全局访问点,或者它变得像一个全局变量。是否可以在没有任何类型的全局变量(包括静态变量)的情况下实现单例。是否可以在 C#.NET 中执行此操作?

4

4 回答 4

3

The problem you are hinting at is that a Singleton becomes like a global var. What it uses is irrelevant.

And the answer would be No. You will always need a static somewhere, you can only defer it. And that kind of defeats the point.

于 2012-11-01T14:18:43.713 回答
2

不,那不会是单身人士。

您可以使用 IoC 容器仅将事物作为单例注入。

于 2012-11-01T14:18:09.597 回答
2

You could implement an interface and then use something like StructureMap. In SM you would build the class like this:

public class Foo : IFoo
{
}

And then you would define, in your container, the following:

ObjectFactory.Initialize(x =>
{
    x.For<IFoo>.Singleton().Use<Foo>();
}

Then you would inject this resource where you needed it:

public class Bar
{
    public Bar(IFoo foo)
    {
    }
}

So, now there will only ever be one instance of the concrete created and then injected into an enumerable number of types that need it.

于 2012-11-01T14:18:42.517 回答
0

我不相信。如果没有静态变量,您将实例存储在哪里?通常,当我想要一个类的单例时,我将所有构造函数设为私有,并提供一个静态方法或属性,如果它尚未创建,它将创建实例,并返回实例。实例本身存储为私有变量,因此访问它的唯一方法是通过提供的方法/属性 - 或反射。

于 2012-11-01T14:19:56.333 回答