单例设计模式是一种软件设计原理,用于将类的实例化限制为最多一个对象。 当仅需要一个对象来协调整个系统中的运作时,单例模式就很有用。 例如,如果您使用的是将日志写入文件的记录器,则可以使用单例类创建此类记录器。
class Singleton
{
public:
~Singleton(){};
Singleton(const Singleton&)=delete;//禁用拷贝构造函数
Singleton& operator=(const Singleton&)=delete;//禁用赋值运算符
static Singleton& get_instance()
{
static Singleton instance;
return instance;
}
private:
Singleton(){};
};
template <typename T>
class Singleton
{
public:
~Singleton(){};
Singleton(const Singleton&) = delete;//禁用拷贝构造函数
Singleton& operator=(const Singleton&) = delete;//禁用赋值运算符
static T& get_instance()
{
static T instance;
return instance;
}
protected:
Singleton(){};
};