示例文章

C++
1
2
3
4
5
6
7
8
9
10
/**
* 实例化一个单例类
*/

class FSingletonTest : public FSingleton<FSingletonTest>
{


}

C++
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 创建单例基类
*/

template<typename Type>
class FSingleton
{

private:
static Type* m_pInstance; //当然也可以采用智能指针包裹 TShharedPtr<Type> m_pInstance

public:
FSingleton()
{
m_pInstance = static_cast<ReturnType>(this);
}
virtual ~FSingleton()
{
m_pInstance=nullptr;
}

virtual void InitSingleton() {}

virtual void ReleasePtr()
{
if (m_pInstance != nullptr)
{
delete m_pInstance;
}
m_pInstance = nullptr;
}

static Type* CreateInstance()
{
if (m_pInstance == nullptr)
{
m_pInstance = new Type();
}
return m_pInstance;
}

static Type& GetInstance()
{
return *m_pInstance;
}

static Type* GetInstancePtr()
{
return m_pInstance;
}


static bool IsValid()
{
return m_pInstance != nullptr;
}
};