为什么使用单子而不是静态方法?[英] Why use a singleton instead of static methods?

本文是小编为大家收集整理的关于为什么使用单子而不是静态方法?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我从未找到有关这些有关帮手/实用程序课程的简单问题的好答案:

  • 为什么我要创建一个单身人士(无状态)而不是使用静态方法?
  • 如果对象没有状态,为什么需要一个对象实例?

推荐答案

通常,单例被用来将某种全局状态引入应用程序. (老实说,比真正必要的更多,但这是另一个话题.)

但是,在一些角案件中,即使是无状态 singleton也可以有用:

  • 您希望在可预见的未来将其扩展到状态.
  • 您需要一个特定的技术原因.示例:c#lock或Java synchronized语句.<<<
  • 您需要继承,即,您希望能够使用相同的接口轻松替换单身顿,但使用相同的实现.
    示例:java中的Toolkit.getDefaultToolkit()方法将返回一个singleton,其确切类型的singleton是系统依赖的.
  • 您想要参考equality sentinel value .
    示例:DBNull.Value在C#.

其他推荐答案

我可以看到使用无状态单例而不是静态方法类别的案例,即依赖注入.

如果您有直接使用的实用程序函数的辅助类别,则会创建隐藏的依赖性;您无法控制谁可以使用它或在哪里.通过无状态单例实例注入相同的助手类,使您可以控制其在哪里以及如何使用,并在需要时替换它/模拟IT/等.

使其成为单身实例,简单地确保您不会分配该类型的任何对象(因为您只需要一个).

其他推荐答案

实际上,我在这里发现了另一个答案:静态方法很难测试.

似乎大多数测试框架都非常适合模拟实例方法,但其中许多人没有以体面的方式处理静态方法的模拟.

本文地址:https://www.itbaoku.cn/post/627577.html

问题描述

I have never found good answers to these simple questions about helper/utility classes:

  • Why would I create a singleton (stateless) instead of using static methods?
  • Why would an object instance be needed if an object has no state?

推荐答案

Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)

However, there are a few corner cases where even a stateless singleton can be useful:

  • You expect to extend it with state in the foreseeable future.
  • You need an object instance for some particular technical reason.
    Example: Synchonization objects for the C# lock or the Java synchronized statement.
  • You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.
    Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
  • You want reference equality for a sentinel value.
    Example: DBNull.Value in C#.

其他推荐答案

I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.

If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.

Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).

其他推荐答案

Actually i've found another answer not mentionned here: static methods are harder to test.

It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.