懒汉模式
class Sigleton
{
private:
Sigleton() { std::cout << "Sigleton constructor" << std::endl; };
~Sigleton();
Sigleton(const Sigleton &other) = delete;
Sigleton &operator=(const Sigleton &) = delete;
public:
static Sigleton *Instance()
{
if (nullptr == instance_)
{
instance_ = new Sigleton();
}
return instance_;
};
static void Test()
{
Sigleton::Instance();
Sigleton::Instance();
}
private:
// declare staic member instance_
static Sigleton *instance_;
};
// define staic member instance_
Sigleton *Sigleton::instance_ = nullptr;
饿汉模式
class Sigleton
{
private:
Sigleton() { std::cout << "Sigleton constructor2" << std::endl; };
~Sigleton();
Sigleton(const Sigleton &other) = delete;
Sigleton &operator=(const Sigleton &) = delete;
public:
static Sigleton *Instance()
{
return instance_;
};
static void Test()
{
Sigleton::Instance();
Sigleton::Instance();
}
private:
// declare staic member instance_
static Sigleton *instance_;
};
// define staic member instance_
Sigleton *Sigleton::instance_ = new Sigleton();