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.

  • 相关阅读:
    蓝桥杯 算法训练 ALGO-118 连续正整数的和
    迭代器和生成器
    字符串格式化
    python 赋值 深浅拷贝
    web.py
    urlib2 标准代码
    left menu
    tab menu
    modal html
    emmet使用
  • 原文地址:https://www.cnblogs.com/chucklu/p/4061834.html
Copyright © 2011-2022 走看看