说明 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