#include "pch.h"
#include <iostream>
using namespace std;
//实现单例步骤:
//1、构造函数私有化。
//2、增加静态私有当前指针变量
//3、提供静态对外接口,可以让用户获得单例
class A {
private:
A()
{
a = new A;
}
public: //外部访问唯一途径
A* getInstace() //相对于new getinstace是静态的
{
return a;
}
private:
static A *a;
};
A *a = NULL; //类外进行初始化
//单例分为懒汉式和饿汉式:
//懒汉式
class singleton_lazy
{
private:
singleton_lazy()
{
cout << "我是懒汉构造函数" << endl;
};
public:
static singleton_lazy *getInstance() //调用时才会new出对象。
{
if (psingleton_lazy == NULL)
{
psingleton_lazy = new singleton_lazy;
cout << "我是懒汉构造函数外导函数" << endl;
}
return psingleton_lazy;
}
private:
static singleton_lazy*psingleton_lazy;
};
singleton_lazy* singleton_lazy::psingleton_lazy = NULL; //初始化置空
//饿汉式
class singleton_hunger
{
private:
singleton_hunger()
{
cout << "饿汉构造函数从main函数开始" << endl;
};
static singleton_hunger *getInstance()
{
/*if (psingleton_hunger == NULL)
{
psingleton_hunger = new singleton_hunger;
}*/
return psingleton_hunger;
}
private:
static singleton_hunger*psingleton_hunger;
};
//初始化即创建对象
singleton_hunger* singleton_hunger::psingleton_hunger = new singleton_hunger;
int main()
{ //单例对象的调用
singleton_lazy *p1 = singleton_lazy::getInstance();
singleton_lazy *p2 = singleton_lazy::getInstance();
if (p1 == p2)
{
cout << "这是一个单例构造" << endl;
}
else {
cout << "这不是一个单例构造" << endl;
}
//psingleton_lazy;
std::cout << "Hello World!\n";
}
【C++】单例模式,饿汉模式和懒汉模式的创建
最新推荐文章于 2024-04-18 20:00:51 发布