具有静态成员的类与单例类
只有静态成员的类不是一种单例设计模式吗? 开设这样的课程有什么缺点吗? 详细的解释会有所帮助。
Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这种类被称为 monostate - 它与单身人士。
为什么使用单态而不是单例? 在他们的原始论文中关于图案,Bell & 克劳福德提出了三个理由(由我解释):
名称我必须承认,我不认为其中任何一个特别引人注目。 另一方面,单态绝对不比单态差。
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):
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.
Robert C. Martin 不久前写了一篇文章,介绍了单态模式和单状态模式之间的差异单例模式。
Robert C. Martin wrote an article some times ago about the differences between the mono state pattern and the singleton pattern.
考虑一系列日志记录类。 它们都实现了“LogMessage(message, file, line_number)”。有些将消息发送到 stderr,有些将电子邮件发送给一组开发人员,有些增加消息频率表中特定消息的计数,有些路由到 /dev/null在运行时,程序检查要使用日志记录技术的参数向量、注册表或环境变量,并使用合适的类中的对象实例化日志记录单例,可能会加载最终用户提供的 DLL 来执行该功能。很难用纯静态单例来复制。
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.
——而不是模式。 当我们谈论类时,我们可以说类实现模式。
静态函数 - 不是成员函数,它们在全局函数上类似。 也许你不需要任何课程?
引用自维基百科:
根据这个定义,您的实现不是单例实现 - 您不使用常见的想法类的一个(或扩展定义中的多个)实例。
但有时(并非总是)将类与所有静态函数和单例模式一起使用 - 没有有意义的区别。
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:
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.
对于单例,所有构造函数都必须是私有的,以便您只能通过函数访问。 但你已经很接近了。
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.