你会认为这是一个单/单例模式? [英] Would you consider this a singleton/singleton pattern?

查看:206
本文介绍了你会认为这是一个单/单例模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象中的Global.asax.cs文件我有一个实例类作为私有字段,可以说是这样的:

Imagine in the Global.asax.cs file I had an instance class as a private field, lets say like this:

private MyClass _myClass = new MyClass();

和我对全球名为GetMyClass(静态方法)获取当前的HttpApplication并返回该实例。

and I had on Global a static method called GetMyClass() that gets the current HttpApplication and returns that instance.

public static MyClass GetMyClass()
{
    return ((Global)HttpContext.Current.ApplicationInstance)._myClass;
}

所以,我可以通过调用Global.GetMyClass()获得当前请求的HttpApplication实例

So I could get the instance on the current requests httpapplication by calling Global.GetMyClass().

请有超过1(全球)的HttpApplication。存在用于每个请求的的HttpApplication和它们汇集/​​共享,所以在真正意义上它不是一个真正的单例。但它确实遵循的模式在一定程度上。

Keep in mind that there is more than 1 (Global)HttpApplication. There is an HttpApplication for each request and they are pooled/shared, so in the truest sense it is not a real singleton. But it does follow the pattern to a degree.

因此​​,作为提出的问题,你会不会考虑这个最起码的Singleton模式?

So as the question asked, would you consider this at the very least the singleton pattern?

你会说,这不应该使用?你会鼓励使用?你会说其一个可能不好的做法像一个真正的单身。

Would you say it should not be used? Would you discourage its use? Would you say its a possibly bad practice like a true singleton.

你能看到,可以从这种类型的使用场景中出现的任何问题?

Could you see any problems that may arise from this type of usage scenario?

或者你会说,它不是一个真正的单身所以它的确定,而不是坏的做法。你会推荐这是在需要每个请求实例的半准单身?如果没有什么其他的模式/建议,你可以使用/放弃?

Or would you say its not a true singleton so its ok, and not bad practice. Would you recommend this as a semi quasi singleton where an instance per request is required? If not what other pattern/suggestion would you use/give?

你用过什么像这样?

我已经使用这个过去的项目,但我不确定如果它的做法,我应该远离。我从来没有在过去的任何问题,但。

I have used this on past projects but I am unsure if its a practice I should stay away from. I have never had any issues in the past though.

请给我你的想法和意见这一点。

Please give me your thoughts and opinions on this.

编辑:我不是问一个单身是什么。而且我认为imprperly使用时,一个单身不好的做法,这是在很多很多很多的情况。那是我。然而,这是不是我想讨论。我想讨论这种情况下我给。谢谢你。

I am not asking what a singleton is. And I consider a singleton bad practice when used imprperly which is in many many many cases. That is me. However, that is not what I am trying to discuss. I am trying to discuss THIS scenario I gave. Thanks.

推荐答案

这是否符合一个Singleton的千篇一律的模式,它仍然同样的问题辛格尔顿缺陷:

Whether or not this fits the cookie-cutter pattern of a Singleton, it still suffers from the same problems as Singleton:


  • 这是一个静态的,具体的参考,并且不能被取代为单独的行为或存根/测试期间嘲笑

  • 您无法继承这一点,preserve这种行为,所以它很容易绕过这个例子单身性质

这篇关于你会认为这是一个单/单例模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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