]> Dogcows Code - chaz/yoink/blob - src/Moof/Manager.hh
reformatting
[chaz/yoink] / src / Moof / Manager.hh
1
2 /*] Copyright (c) 2009-2010, Charles McGarvey [**************************
3 **] All rights reserved.
4 *
5 * vi:ts=4 sw=4 tw=75
6 *
7 * Distributable under the terms and conditions of the 2-clause BSD license;
8 * see the file COPYING for a complete text of the license.
9 *
10 **************************************************************************/
11
12 #ifndef _MOOF_MANAGER_HH_
13 #define _MOOF_MANAGER_HH_
14
15 /**
16 * @file Manager.hh
17 * A library is a collection of named objects of the same type. Libraries
18 * use reference counting to automagically delete objects which no longer
19 * have any interested code.
20 */
21
22 #include <string>
23
24 #include <boost/shared_ptr.hpp>
25
26 #include <Moof/Hash.hh>
27
28
29 namespace Mf {
30
31
32 template <class T>
33 class Manager
34 {
35 public:
36
37 Manager() :
38 mRetainCount(1) {}
39
40 const std::string& getName() const
41 {
42 return mName;
43 }
44
45 static boost::shared_ptr<T> getInstance(const std::string& name)
46 {
47 return boost::shared_ptr<T>(retain(name), &release);
48 }
49
50 private:
51
52 typedef stlplus::hash<std::string,T*,getHash> PtrMap;
53
54 static PtrMap mPtrMap;
55 std::string mName;
56 unsigned mRetainCount;
57
58 static T* retain(const std::string& name)
59 {
60 typename PtrMap::iterator it = mPtrMap.find(name);
61
62 if (it != mPtrMap.end())
63 {
64 ++((*it).second->mRetainCount);
65 return (*it).second;
66 }
67 else
68 {
69 T* newObj(new T);
70 if (newObj)
71 {
72 newObj->mName = name;
73 newObj->init(name);
74 mPtrMap.insert(std::make_pair(name, newObj));
75 }
76 return newObj;
77 }
78 }
79
80 static void release(T* obj)
81 {
82 if (--(obj->mRetainCount) == 0)
83 {
84 mPtrMap.erase(obj->mName);
85 delete obj;
86 }
87 }
88 };
89
90 template <class T>
91 stlplus::hash<std::string,T*,getHash> Manager<T>::mPtrMap;
92
93
94 } // namespace Mf
95
96 #endif // _MOOF_MANAGER_HH_
97
This page took 0.034387 seconds and 4 git commands to generate.