static class and singleton

前端 未结 5 1641
谎友^
谎友^ 2020-12-14 21:04

Isn\'t a class with all static members/methods a kind of singleton design pattern? Is there any disadvantage in particular of having such classes? A detailed explanation wo

相关标签:
5条回答
  • 2020-12-14 21:17

    Robert C. Martin wrote an article some times ago about the differences between the mono state pattern and the singleton pattern.

    0 讨论(0)
  • 2020-12-14 21:24

    Consider a family of Logging classes. They all implement "LogMessage(message, file, line_number). Some send messages to stderr, some send email to a set of developers, some increment the count of the particular message in a message-frequency table, some route to /dev/null. At runtime, the program checks its argument vector, registry, or environment variables for which Logging technique to use and instantiates the Logging Singleton with an object from a suitable class, possibly loading an end-user-supplied DLL to do so. That functionality is tough to duplicate with a pure static Singleton.

    0 讨论(0)
  • 2020-12-14 21:26

    class with all static members/methods a kind of singleton design pattern

    Class - not pattern. When we talk about classes we can say class implements pattern.


    Static functions - is not member functions, they are similar on global functions. Maybe you don't need any class?

    Quote from wikipedia:

    In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.

    By this definition your implementation is not singleton implementation - you don't use common idea One (or several in extended definition) instance of class.

    But sometimes (not always) usage of class with all static functions and singleton pattern - not have meaningful difference.

    0 讨论(0)
  • 2020-12-14 21:31

    This kind of class is known as a monostate - it is somewhat different from a singleton.

    Why use a monostate rather than a singleton? In their original paper on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):

    • More natural access syntax
    • singleton lacks a name
    • easier to inherit from

    I must admit, I don't find any of these particularly compelling. On the other hand, the monostate is definitely no worse than the singleton.

    0 讨论(0)
  • 2020-12-14 21:35

    For a singleton all constructors have to be private, so that you can access only through a function. But you're pretty close to it.

    0 讨论(0)
提交回复
热议问题