如何在 C++ 中编写单例类?
单例设计模式是一种软件设计原则,用于将类的实例化限制为一个对象。当完全需要一个对象来协调系统中的操作时,则很有用。例如,如果您使用写入文件日志的记录器,则可以使用单例类来创建这样的记录器。您可以使用以下代码创建一个单例类。
示例
#include <iostream>
using namespace std;
class Singleton {
static Singleton *instance;
int data;
// Private constructor so that no objects can be created.
Singleton() {
data = 0;
}
public:
static Singleton *getInstance() {
if (!instance)
instance = new Singleton;
return instance;
}
int getData() {
return this -> data;
}
void setData(int data) {
this -> data = data;
}
};
//Initialize pointer to zero so that it can be initialized in first call to getInstance
Singleton *Singleton::instance = 0;
int main(){
Singleton *s = s->getInstance();
cout << s->getData() << endl;
s->setData(100);
cout << s->getData() << endl;
return 0;
}输出
0 100
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP