在蓋莫游戲引擎的書寫過程中先后書寫了資源管理器,場景管理器,模型管理器等管理器類.之后感覺很有必要寫一個泛型的管理器類了.這個可以少做一些重復性的工作了。
管理器類無非就是獲取當前對象個數,對象生成,對象按名索取等等
經過考慮,草料書寫如下:
1 namespace core
2 {
3
4 ////////////////////////////////////////////////////////////
5 //! 定義引擎泛型管理器類
6 ////////////////////////////////////////////////////////////
7 template<class Obj = Object, class Type = std::string>
8 class Manager
9 {
10 public:
11 typedef Type ThisType;
12 typedef Obj ThisObj;
13 typedef std::map<ThisType,RefPtr<ThisObj> > Table;
14 //! typedef std::map<ThisType,RefPtr<ThisObj> >::iterator TableItr;
15
16 ////////////////////////////////////////////////////////
17 //! 構造,析構場景管理器
18 ////////////////////////////////////////////////////////
19 Manager(){}
20 virtual ~Manager() = 0;
21 public:
22
23 ////////////////////////////////////////////////////////////
24 /// 獲取當前管理器中的對象個數
25 ////////////////////////////////////////////////////////////
26 inline uint32 GetObjectNumber()const{return objects.size();}
27
28 ////////////////////////////////////////////////////////////
29 /// 檢測當前管理器中是否存在對象
30 ////////////////////////////////////////////////////////////
31 inline bool HasObject()const{return !objects.empty();}
32
33 ////////////////////////////////////////////////////////////
34 /// 獲取給定索引的對象(如果對象不存在則生成一個新的對象)
35 ////////////////////////////////////////////////////////////
36 inline RefPtr<Object> GetObject(const Type& name)
37 {
38 if(objects.find(name) != objects.end())
39 return objects[name];
40 return NULL;
41 }
42
43 ////////////////////////////////////////////////////////////
44 /// 生成一個新的對象
45 ////////////////////////////////////////////////////////////
46 virtual RefPtr<ThisObj> CreateObject(const Type& name) = 0;
47
48 ////////////////////////////////////////////////////////////
49 /// 銷毀指定名字的對象
50 ////////////////////////////////////////////////////////////
51 inline bool KillObject(const Type& name)
52 {
53 std::map<std::string,RefPtr<Model> >::iterator itr = objects.find(name);
54 if(itr == objects.end())
55 return false;
56 objects.erase(name);
57 return NULL;
58 }
59
60 ////////////////////////////////////////////////////////////
61 /// 管理器對象清空
62 ////////////////////////////////////////////////////////////
63 inline void ClearObject(){objects.clear();}
64 protected:
65 Table objects;
66 };
67
68 template<class Obj, class Type>
69 Manager<Obj,Type>::~Manager()
70 {
71 ClearObject();
72 }
73
其中使用std::map作為基本的管理器容器
同時其中CreateObject函數是一個虛擬函數需要重載之
然后我們就可以這樣寫具體的的管理器了.
比如:
1 class ModelManager : public Manager<Model,std::string>
2 {
3 public:
4 RefPtr<Model> CreateObject(const std::string &);
5 };