概述
单例模式的目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点。
优点
提供了对唯一实例的受控访问。
缺点
单例类的职责过重,在一定程度上违背了“单一职责原则”。
类图
代码块
1. 饿汉型
#include <iostream>
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 <iostream>
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;
}