c# - 使用单例设计模式时,首选哪种结构,为什么?

标签 c# asp.net design-patterns mvp

除了“what is so bad about singletons”:-),我有一个在业务逻辑层使用单例的 ASP.NET Web 应用程序,因此:

public class MyBusinessService
{
    private static MyBusinessService mInstance = null;

    public static MyBusinessService Instance
    {
        get { return mInstance; }
    }

    static MyBusinessService()
    {
        mInstance = new MyBusinessService();
    }
}

我们主要将它们用于 Model View Presenter 中的依赖项架构。

它们还可以通过以下两种方式之一跨业务逻辑类使用。首先通过以下方式:

var myService = new MyBusinessService();
myService.DoSomething();
myService.DoSomethingElse();

或者,可以通过以下方式使用:

MyBusinessService.Instance.DoSomething();
MyBusinessService.Instance.DoSomethingElse();

首选哪种构造,为什么?我对单例模式本身是好是坏不感兴趣。

更新: 好的,这个问题似乎很受欢迎。我猜是准单例。两全其美!我对重构模式/反模式/代码 hell 并不感兴趣。我更感兴趣的是了解所描述的两种用法的影响。

我们的 View (ASP.NET 页面)如下所示:

var presenter = new SomeViewPresenter(this, MyBusinessService.Instance);

但也可以实现为:

var presenter = new SomeViewPresenter(this, new MyBusinessService());

在这种情况下,我更喜欢前者。注意singleton这个词的用法和上面的不正确用法都理解了,但是就代码而言,这两个原始选项的结果是什么?

最佳答案

后者是首选,因为前者的行为不像单例 - 您正在实例化一个新实例而没有任何保护措施来停止多个现有实例。

如果您将这些保护措施放在适当的位置,则后者可能是您最终得到的代码。您也不需要一直使用该属性:

var service = MyBusinessService.Instance;
service.This();
service.That();

我也以一些怀疑的态度看待 ASP.NET 中的静态,这是来自 WinForms 开发人员:-)

关于c# - 使用单例设计模式时,首选哪种结构,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7904465/

相关文章:

c# - 如何在 ASP.Net Core 1.1 中响应.Cookies.Append()?

c# - C# CoClass 属性有什么作用?

c# - 静态方法的含义

asp.net - Visual Studio 2010 sp1 找不到类型或命名空间名称 'xxx'(是否缺少 using 指令或程序集引用?)

wpf - 为什么不使用部分类以MVVM模式构建ViewModel?

c# - 3 维波的法线

c# - 带有 ref 对象参数的方法

python - 将枚举映射到函数的最佳方法

mongodb - NoSQL(Mongo)的面向文档的数据抽象层?

c# - 删除 Split View中的单选按钮图标 Windows 通用应用程序