【问题标题】:Is this C++ singleton pattern and method exposure a good practice?这种 C++ 单例模式和方法公开是一个好习惯吗?
【发布时间】:2014-08-23 18:30:39
【问题描述】:

我想要一个单例类并公开它的一些方法,这些方法直接在实例上工作。下面的代码是一个好的模式吗?

class Singleton
{
public:
    static Singleton& get()
    {
        // the easiest way to implement a singleton class

        static Singleton instance;

        return instance;
    }

    static void publicMethodOne()
    {
        // "redirecting" the call to the instance itself

        get().instancePublicMethodOne();
    }

    static void publicMethodTwo()
    {
        // "redirecting" the call to the instance itself

        get().instancePublicMethodTwo();
    }

private:
    Singleton() {}
    Singleton(const Singleton& s) {}
    Singleton& operator=(const Singleton& s) {}

    void instancePublicMethodOne()
    {
        // do stuff
    }

    void instancePublicMethodTwo()
    {
        // do stuff
    }

    void privateMethodOne()
    {
        // privately do stuff
    }
};


// call from outside
Singleton::publicMethodOne();

这基本上将每个静态和公共方法调用重定向到实例,每个静态和公共方法在实例内部都有一个pair方法。

编辑:我想使用单例模式,这是肯定的。我的问题是这种全局公开实例方法的模式是否好。

【问题讨论】:

  • 单例模式好?一般来说:没有。单例几乎是一种反模式。在几乎所有情况下,Singleton 都被滥用为神奇地美化了全局数据。但是请注意,无论是否标记为 Singleton,全局可变数据总是不好的。
  • 我想使用单例,这不是问题。我在问我将实例方法公开为全球可用的模式是否良好。
  • 这似乎违反了 DRY。
  • 确实,这就是我要问的原因。感觉不对,但我不知道有什么其他的解决方案。
  • 你刚刚写了一堆无用的代码来模拟命名空间中的函数。

标签: c++ design-patterns singleton


【解决方案1】:

自己比较这两个调用:

Singleton::publicMethodOne();
Singleton::get().publicMethodOne();

你只需在这个静态方法中调用Singleton::get。这样做没有多大意义。它只会膨胀代码。

【讨论】:

  • 你是对的,我所做的只是在静态方法中调用 get(),但由于它是一个单例并且我想简化公共 API,我认为这会很好,因为用户不必到处写 get()。
  • 嗯,你也是对的。但是那个公共 API 可能很大,所以这个类会变得比它应得的更大。
猜你喜欢
  • 1970-01-01
  • 2012-08-12
  • 2010-09-11
  • 1970-01-01
  • 2012-08-29
  • 2018-11-17
  • 2017-02-20
  • 2019-06-04
  • 2023-03-14
相关资源
最近更新 更多