【发布时间】: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