design pattern singleton
simuruk wiki
멀티스레드 개발에서 일관성을 보장해주는 방식
- 생성자 막기
- 소멸자 막기
- getter
- multithread
// C++
Foo* Foo::Instance() {
if(pinstance == nullptr) {
lock_guard<mutex> lock(m_);
if(pinstance == nullptr) {
pinstance = new Foo();
}
}
return pinstance;
}
// JAVA
public static synchronized singleton getInstance () {
if (instance == null)
instance = new ThreadSafeInitalization();
return instance;
}
접기 1. 주소 값을 이용한 방식
class yh_singleton
{
public:
static yh_singleton& getInstanse(){
static yh_singleton instance;
return instance;
};
int num;
private:
yh_singleton(){};
yh_singleton(const yh_singleton& other);
yh_singleton& operator=(yh_singleton& cls);
~yh_singleton(){};
};
yh_singleton& yh= yh_singleton::getInstanse();
yh.num= 4;
2. 포인터를 이용한 방식
class yh_singleton
{
public:
static yh_singleton* getInstanse(){
static yh_singleton instance;
return &instance;
};
int num;
private:
yh_singleton(){};
yh_singleton(const yh_singleton& other);
yh_singleton& operator=(yh_singleton& cls);
~yh_singleton(){};
};
yh_singleton* yh= yh_singleton::getInstanse();
yh->;num= 4;
3. 템플릿 싱글톤
template <typename T>
class yh_singleton
{
public:
static T* getInstance()
{
if (instance == NULL)
instance = new T;
return instance;
};
static void destroyInstance()
{
if (instance)
{
delete instance;
instance = NULL;
}
};
private:
static T* instance;
protected:
yh_singleton(const yh_singleton& other);
yh_singleton& operator=(yh_singleton& cls);
yh_singleton();
virtual ~yh_singleton(){};
};
template <typename T>T * yh_singleton<T>::instance = NULL;
class ojectA : public yh_singleton<ojectA>
{
public:
ojectA();
~ojectA();
int a;
};