单例模式 - 哪个是更好的实践?
我有一个单例,我正在争论使用一些静态方法来向客户端隐藏单例的使用是否是一种不好的做法。例如:
Singleton::Instance()->Foo();
VS。
Singleton::FooHelper();
FooHelper 的定义位置:
class Singleton
{
...
static void FooHelper()
{
Singleton::Instance()->Foo();
}
...
}
第二个解决方案被认为是不好的做法吗?我不会为 Singleton 的所有方法创建辅助函数,而只会为客户端代码非常频繁使用的方法创建辅助函数。
I have a singleton, and I'm debating whether it would be bad practice to have some static methods that sort of hide the singleton's usage from the client. For example:
Singleton::Instance()->Foo();
Vs.
Singleton::FooHelper();
Where FooHelper is defined:
class Singleton
{
...
static void FooHelper()
{
Singleton::Instance()->Foo();
}
...
}
Is the second solution considered bad practice? I wouldn't be making helper functions for all the methods of Singleton, just the ones that are used very frequently by the client code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种想法是完全摆脱单身人士。使其成为系统中具有适当所有者的适当类,其他类必须去获取该对象。然后你就可以像访问“普通”对象一样访问它,而且它看起来不会那么刺耳。
许多人认为单例是一种反模式。我发现它们的一个大问题是,当您有一天发现需要时,它们使您很难概括您的代码。随着计算机变得更快并获得更多内核,在我工作的地方,我们现在发现自己希望能够在同一台机器上同时运行多个主程序。这样做的最大挑战是我们愚蠢地编码的所有单例。
尝试一次不使用单例,看看效果如何。
One idea would be to get rid of the singleton altogether. Make it a proper class with a proper owner in your system, which other classes have to go to get hold of that object. Then you can access it like a "normal" object, and it won't look so jarring.
Many folks consider singletons an anti-pattern. The big problem with them I've found is they make it very hard to generalize your code when you find a need for that one day. As computers get faster and get more cores, where I work we now find ourselves wanting the ability to run more than one of our main program on the same machine at once. The biggest challenge to doing this is all the singletons we foolishly coded up.
Try doing without the singleton this once and see how it works out for you.
只要 1° 原始
Foo()
方法仍然公开可用,并且 2° 命名方案明显表明FooHelper()
相当于在实例上调用Foo()
。当然,如果您发现自己总是调用
FooHelper()
而从不调用Foo()
,请重新考虑您的设计:单例的要点(而不是简单的全局变量)命名空间中的函数方法)的特点是它是一个对象 - 因此至少代码的某些部分应该这样使用它。This is not bad practice as long as 1° the original
Foo()
method is still publicly available and 2° the naming scheme makes it obvious thatFooHelper()
is equivalent to callingFoo()
on the instance.Of course, if you find yourself always calling
FooHelper()
and never callingFoo()
, reconsider your design: the point of a singleton (as opposed to a plain global-functions-in-namespace approach) is that it's an object — so at least some parts of your code should be using it as such.