什么时候应该使用单例模式而不是静态类?

问题描述:

在使用 singleton 与静态类别之间确定设计注意事项。在这样做的时候,你*对比了两个,所以你可以想出的对比也可以用来展示你的思维过程!此外,每个访问者都喜欢看到说明性的例子。

Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)


  • 单身人士可以实现接口并从其他类继承

  • 单身人士可以懒惰加载。只有当它实际需要如果初始化包括昂贵的资源加载或数据库连接,那非常方便。

  • 单身人士提供一个实际的对象。

  • 单身人士可以扩展到工厂。背后的对象管理是抽象的,所以它更好的维护和更好的代码。

    • Singletons can implement interfaces and inherit from other classes.
    • Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.
    • Singletons offer an actual object.
    • Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.