【C++】单例模式,饿汉模式和懒汉模式的创建

#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";
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值