单例模式 - 哪个是更好的实践?

发布于 2024-10-11 17:28:58 字数 426 浏览 2 评论 0原文

我有一个单例,我正在争论使用一些静态方法来向客户端隐藏单例的使用是否是一种不好的做法。例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

極樂鬼 2024-10-18 17:28:58

一种想法是完全摆脱单身人士。使其成为系统中具有适当所有者的适当类,其他类必须去获取该对象。然后你就可以像访问“普通”对象一样访问它,而且它看起来不会那么刺耳。

许多人认为单例是一种反模式。我发现它们的一个大问题是,当您有一天发现需要时,它们使您很难概括您的代码。随着计算机变得更快并获得更多内核,在我工作的地方,我们现在发现自己希望能够在同一台机器上同时运行多个主程序。这样做的最大挑战是我们愚蠢地编码的所有单例。

尝试一次不使用单例,看看效果如何。

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.

回忆凄美了谁 2024-10-18 17:28:58

只要 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 that FooHelper() is equivalent to calling Foo() on the instance.

Of course, if you find yourself always calling FooHelper() and never calling Foo(), 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文