생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 유일하게끔 사용하는 디자인 패턴
#include <iostream>
#include <string>
using namespace std;
class Singleton {
public:
static Singleton* New(string name) {
static Singleton *instance = nullptr;
if (instance == nullptr) instance = new Singleton(name);
return instance;
}
void print() {
cout << "my name is " << _name << "\n";
}
private:
string _name = "";
Singleton() {}
Singleton(string name) :_name(name) {}
};
int main() {
Singleton *instance = Singleton::New("jihoon");
Singleton *instance2 = Singleton::New("taehoon");
instance->print();
instance2->print();
return 0;
}
| cs |