①单例模式
特点:
1、单例类智能有一个实例对象
2、改单例对象必须由单例类自行创建
3、单例类对外提供一个访问该单例的全局访问点
实现:
1、将构造函数设置为私有的,保证外部不能不能调用构造函数创建对象
2、提供一个静态成员函数,使得外部可以通过该函数获取到单例
案例:
cocos的导演类CCDirector、图片缓存类CCTextureCache等
优点:
简单易用,限制一个类只有一个实例,降低创建多个对象可能引起的内存问题的风险,包括内存泄漏、内存占用的问题
#include <iostream>
using namespace std;
class Test {
private :
Test() {};
static Test* instanece;
int m_x;
public:
static Test* getInstance();
int getX();
void setX(int n);
};
Test* Test::instanece = nullptr;
Test* Test::getInstance() {
if (instanece == nullptr) {
instanece = new Test();
instanece->m_x = 0;
}
return instanece;
}
void Test::setX(int n) {
m_x = n;
}
int Test::getX() {
return m_x;
}
int main() {
cout << Test::getInstance()->getX() << endl;//输出0
Test::getInstance()->setX(100);
cout << Test::getInstance()->getX() << endl;//输出100
system("pause");
}
②简单工厂模式
引用文章