栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++设计模式之单例模式

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++设计模式之单例模式

懒汉式,只有对象调用时,才创建对象

饿汉式程序运行自动创建对象

//饿汉式
class singleton_hungry
{
public://2、提供公共静态函数接口,其他类调用该类只能通过该接口
	static singleton_hungry* getInstance()
	{
		return pSingleton;
	}
private:
	singleton_hungry() {
	}// 1、构造函数私有化,其他类不可调用(Protected继承后也可用)
	static singleton_hungry *pSingleton;
};
singleton_hungry *singleton_hungry::pSingleton = new singleton_hungry;//3、类外创建变量,static关键值可以通过域名创建对象


//懒汉式
class singleton_lazy
{
public://2、提供公共静态函数接口,其他类调用该类只能通过该接口
	static singleton_lazy* getInstance()
	{
		if (pSingleton == NULL)
		{
			pSingleton = new singleton_lazy;
		}
		return pSingleton;
	}
private:
	singleton_lazy() {}// 1、构造函数私有化,其他类不可调用(Protected继承后也可用)
	static singleton_lazy *pSingleton;
};
singleton_lazy *singleton_lazy::pSingleton = new singleton_lazy;//3、类外创建变量,static关键值可以通过域名创建对象

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1017956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号