单例模式
饿汉模式
class singlePattern
{
private:
singlePattern() {};
static singlePattern* p;
public:
static singlePattern* instance();
class CG
{
public:
~CG()
{
if (singlePattern::p != nullptr)
{
delete singlePattern::p;
singlePattern::p = nullptr;
}
}
};
};
singlePattern* singlePattern::p = new singlePattern();
singlePattern* singlePattern::instance()
{
return p;
}
懒汉模式
class singlePattern
{
private:
static singlePattern* p;
singlePattern(){}
public:
static singlePattern* instance();
class CG
{
public:
~CG()
{
if (singlePattern::p != nullptr) {
delete singlePattern::p;
singlePattern::p = nullptr;
}
}
};
};
singlePattern* singlePattern::p = nullptr;
singlePattern* singlePattern::instance()
{
if (p == nullptr)
{
return new singlePattern();
}
return p;
}