[Design Pattern] 싱글톤 패턴 더 알아보기 - 2

template singleton

템플릿을 통해 싱글톤을 일반화해 구현할 수 있다. 코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
template <typename T>
class TemplateSingleton
{
static T* instance;
static std::mutex Mutex;

static void destroy()
{
if(instance != nullptr)
delete instance;
}

protected:
TemplateSingleton() {}
virtual ~TemplateSingleton() {}
TemplateSingleton(const TemplateSingleton &singleton) = delete;

public:
static T* getInstance()
{
if(instance == nullptr)
{
std::lock_guard<std::mutex> lock(Mutex);
if(instance == nullptr)
{
instance = new T();
atexit(destroy);
}
}

return instance;
}
};

template <typename T> T* TemplateSingleton <T>::instance = nullptr;
template <typename T> std::mutex TemplateSingleton <T>::Mutex;

사용은 다음과 같다.

1
2
3
class test : public TemplateSingleton<test>
{
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/13/Design%20Pattern/IntermediateSingleton2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.