创建型模式 - 单例模式

创建型模式 - 单例模式,第1张

创建型模式 - 单例模式 概述

单例模式的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点。

优点

提供了对唯一实例的受控访问。

缺点

单例类的职责过重,在一定程度上违背了“单一职责原则”。

类图

 

代码块

1. 饿汉型 

#include 

using namespace std;

class God
{
public:
	static God *getInstance() {
		return m_god;		
	}

	void show() {
		cout << "i am god" << endl;
	}
private:
	static God *m_god;
};

God *God::m_god = new God();;

int main()
{
	God *god = God::getInstance();
	god->show();	
	return 0;
}

2. 懒汉型

#include 

using namespace std;

class God {
public:
	static God *getInstance() {
		if(m_god == NULL){
			m_god = new God();
		}
		return m_god;		
	}

	void show() {
		cout << "i am god" << endl;
	}
private:
	static God *m_god;
};

God *God::m_god = NULL;

int main()
{
	God *god = God::getInstance();
	god->show();
	return 0;
}
参考

5. 单例模式 — Graphic Design Patterns

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5717367.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存