싱글 톤없이이 클래스의 단일 인스턴스를 만들려면 어떻게해야하며 다른 클래스가 전역 적으로 선언하지 않고도 액세스 할 수 있도록 어떻게 선언 할 수 있습니까?C++이 클래스와 싱글 톤에 대한 전역 선언에 대한 좋은 대안이 있습니까?
더 나은 이해를위한 코드 (특히 코멘트)을 읽어 보시기 바랍니다 :
#include <iostream>
#include <vector>
// The only class that will be using this class is Obj...
// There can only be a single instance of ObjManager but how can I do that
// without singleton???
class ObjManager
{
friend class Obj;
int i;
};
// Since I cannot think of a better way of accessing the SAME and ONLY ObjManager, I
// have decided to declare a global instance of ObjManager so every instance of
// Obj can access it.
ObjManager g_ObjManager;
class Obj
{
friend class ObjManager;
public:
void Set(int i);
int Get();
};
void Obj::Set(int i) {
g_ObjManager.i += i;
};
int Obj::Get() {
return g_ObjManager.i;
};
int main() {
Obj first_obj, second_obj;
first_obj.Set(5);
std::cout << second_obj.Get() << std::endl; // Should be 5.
second_obj.Set(10);
std::cout << first_obj.Get() << std::endl; // Should be 15.
std::cin.get();
return 0;
};
God 객체가 필요하지 않은 분명한 이유가 없습니다. 당신이 프로그래머 일 때 하나님은 의자와 모니터 사이에 있고, 다른 사람에게 그 일을 넘겨 줄 수는 없습니다. –
이것이 싱글 톤 패턴의 핵심은 아닌가? 왜 그걸하지 않고 왜 그렇게하고 싶습니까? – Barmar
당신이하고있는 일과 함께, 정적 멤버로 똑같은 것을 성취 할 수 있습니다. –