-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject_pool_pattern.cpp
More file actions
79 lines (61 loc) · 1.47 KB
/
object_pool_pattern.cpp
File metadata and controls
79 lines (61 loc) · 1.47 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <vector>
class Resource{
int m_iVal;
public:
Resource() : m_iVal(0) {}
void setVal(int val){
m_iVal = val;
}
int getVal(){
return m_iVal;
}
void resetVal(){
m_iVal = 0;
}
};
class ObjectPool{
private:
static ObjectPool* m_pInstance;
std::vector<Resource*> m_vResources;
ObjectPool(){}
public:
static ObjectPool* getInstance(){
if(m_pInstance == NULL){
m_pInstance = new ObjectPool;
}
return m_pInstance;
}
Resource* getResource(){
if(m_vResources.size() > 0){
std::cout << "Give ready source!" << std::endl;
Resource* pResource = m_vResources.back();
m_vResources.pop_back();
return pResource;
}
else{
std::cout << "No ready source, create new one!" << std::endl;
return new Resource;
}
}
void returnResource(Resource* pResource){
pResource->resetVal();
m_vResources.push_back(pResource);
}
};
ObjectPool* ObjectPool::m_pInstance = NULL;
int main(){
ObjectPool* pObjectPool = ObjectPool::getInstance();
Resource* first = pObjectPool->getResource();
first->setVal(1);
std::cout << "First object val: " << first->getVal() << std::endl;
Resource* second = pObjectPool->getResource();
second->setVal(2);
std::cout << "Second object val: " << second->getVal() << std::endl;
pObjectPool->returnResource(first);
pObjectPool->returnResource(second);
Resource* third = pObjectPool->getResource();
third->setVal(3);
std::cout << "Third object val: " << third->getVal() << std::endl;
return 0;
}