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

查看:116
本文介绍了为什么使用单例而不是静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有找到关于帮助/实用程序类的这些简单问题的很好的答案:

I've 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?

推荐答案

单例用于向应用程序引入某种全局状态。如果它是无状态的,我也没有看到使用单例的点,除非

A singleton is used to introduce some kind of global state to an application. If it is stateless, I also don't see the point of using a singleton, unless


  • 你希望在可预见的未来或

  • 您需要一个对象实例,用于某些特定的技术原因(例如,对于C#锁定语句,虽然这已经相当牵强了)或

  • 你需要继承,即,你想要能够轻松地替换你的单身与另一个一个使用相同的接口但是不同的实现。例如,Java中的 Toolkit.getDefaultToolkit()方法将返回其确切类型与系统相关的单例。

  • you expect to extend it with state in the foreseeable future or
  • you need an object instance for some particular technical reason (for example, for the C# lock statement, although this is already quite far-fetched) or
  • 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. For example, the Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.

这篇关于为什么使用单例而不是静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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