코딩/C++
[C ++ 디자인 패턴] Singleton 패턴이란 ?
영넌
2020. 12. 4. 05:10
Singleton 패턴
디자인 패턴은 정석이라고 생각하면 된다. 그 중에 싱글톤 패턴은 클래스로부터 오직 한 개의 객체만 생성되도록 하는 방법이다.
이미 만들어진 객체가 있는 상태에서 또 다시 객체 생성 호출이 왔을 경우, static 키워드를 이용하여 원래 만들어진 객체의 주소를 넘겨주는 방식으로 만들어보자
class Car
{
private:
Car() {}
static Car* instance;
public:
static Car* getInstance() {
if (instance != nullptr) {
return instance;
}
else {
instance = new Car();
return instance;
}
}
};
Car* Car::instance = nullptr;
int main() {
Car* c = Car::getInstance();
Car* d = Car::getInstance();
Car* e = Car::getInstance();
cout << " c addr: " << c << endl;
cout << " d addr: " << d << endl;
cout << " e addr: " << e << endl;
return 0;
}