单例模式(Singleton)
1、目的:保证一个类只创建一个对象。
2、实现:构造函数私有化,确保类外不能创建对象,该类不能被继承。
简单的理解就是一个类有且只有一个对象。例如:资源管理器,LOL等等。
不多说了上代码:
#include<iostream>
using namespace std;
class Singleton {
private:
int x;
static Singleton* Instance;
Singleton() {
x = 0;
cout<<"无参构造"<<endl;
}
Singleton(int x) {
this->x = x;
cout<<"含参构造"<<endl;
}
~Singleton() {
cout<<"析构函数"<<endl;
}
public:
static Singleton* Create(){//创建
if(!Instance) {
Instance = new Singleton();
cout<<"成功创建"<<endl;
return Instance;
}
}
void Delete() {//释放
delete this;
}
};
Singleton* Singleton::Instance = NULL;
int main(void) {
Singleton* p;
p = Singleton::Create();
p->Delete();
return 0;
}
笔者也是刚刚接触设计模式,希望大家共同探讨,共同进步!有什么问题或者什么错误尽管留言!