zoukankan      html  css  js  c++  java
  • 单例模式和静态类的区别

    http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern

    问题

    What real (i.e. practical) difference exists between a static class and a singleton pattern?

    Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?

    第一个回答

    What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

    The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

    Imagine the singleton implements an interface Foo, and you have a method taking a Foo as a parameter.

    With that setup, callers can choose to use the singleton as the implementation - or they could use a different implementation.

    The method is decoupled解耦 from the singleton.

    Compare that with the situation where the class just has static methods - every piece of code which wants to call those methods is tightly coupled to the class,

    because it needs to specify which class contains the static methods. 

    第二个回答

    The true answer is by Jon Skeet, on another forum here.

    A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

    A static class allows only static methods.

  • 相关阅读:
    sed command
    【Python3】作用域(局部变量、全局变量)
    【Python3】函数与参数
    【Python3】编程范式
    【Python3】字符解码与编码
    【Python3】文件操作
    【Python3】集合
    【Python3】目录
    【Python3】字典
    【Python3】字符串操作
  • 原文地址:https://www.cnblogs.com/chucklu/p/4061834.html
Copyright © 2011-2022 走看看