我知道单例只允许一个对象的一个实例。单例中声明的每个方法都只会对该对象进行操作。我想知道为什么不简单地声明一个可以实现相同目标的全局对象?
我肯定忘记了什么。如果单例存在,则必须有特定的用途或有助于实现特定的机制。
例如:
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton sg;
return sg;
}
void function();
};
Run Code Online (Sandbox Code Playgroud)
将与以下相同:
class NotSingleton
{
public:
NotSingleon();
~NotSingleton()
void function();
};
NotSingleton nsg;
Run Code Online (Sandbox Code Playgroud)
但是,没有什么可以阻止我使用多个实例NotSingleton