싱글톤 디자인 패턴은 클래스의 인스턴스화를 하나의 개체로 제한하는 데 사용되는 소프트웨어 디자인 원칙입니다. 이는 시스템 전체에서 작업을 조정하는 데 정확히 하나의 개체가 필요한 경우에 유용합니다. 예를 들어 파일에 로그를 쓰는 로거를 사용하는 경우 싱글톤 클래스를 사용하여 이러한 로거를 만들 수 있습니다. 다음 코드를 사용하여 싱글톤 클래스를 생성할 수 있습니다.
예시
#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