1 | /*! |
---|
2 | @file ClassFactory.h |
---|
3 | @brief Definition of the ClassFactory class |
---|
4 | |
---|
5 | The ClassFactory is able to create new objects of a specific class. |
---|
6 | */ |
---|
7 | |
---|
8 | #ifndef _ClassFactory_H__ |
---|
9 | #define _ClassFactory_H__ |
---|
10 | |
---|
11 | #include "Identifier.h" |
---|
12 | |
---|
13 | namespace orxonox |
---|
14 | { |
---|
15 | // ############################### |
---|
16 | // ### ClassFactory ### |
---|
17 | // ############################### |
---|
18 | //! The ClassFactory is able to create new objects of a specific class. |
---|
19 | template <class T> |
---|
20 | class ClassFactory : public BaseFactory |
---|
21 | { |
---|
22 | public: |
---|
23 | static bool create(); |
---|
24 | BaseObject* fabricate(); |
---|
25 | |
---|
26 | private: |
---|
27 | ClassFactory() {} // Don't create |
---|
28 | ClassFactory(const ClassFactory& factory) {} // Don't copy |
---|
29 | ~ClassFactory() {} // Don't delete |
---|
30 | |
---|
31 | static T* createNewObject(); |
---|
32 | }; |
---|
33 | |
---|
34 | /** |
---|
35 | @brief Adds the ClassFactory to the Identifier of the same type and creates a new object to retrieve the parents. |
---|
36 | @return True, because the compiler only allows assignments before main() |
---|
37 | */ |
---|
38 | template <class T> |
---|
39 | bool ClassFactory<T>::create() |
---|
40 | { |
---|
41 | // Add the ClassFactory to the Classidentifier of type T |
---|
42 | ClassIdentifier<T>::getIdentifier()->addFactory(new ClassFactory<T>); |
---|
43 | |
---|
44 | // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards. |
---|
45 | ClassIdentifier<T>::getIdentifier()->startCreatingHierarchy(); |
---|
46 | #if HIERARCHY_VERBOSE |
---|
47 | std::cout << "*** Create Factory -> Create Class\n"; |
---|
48 | #endif |
---|
49 | BaseObject* temp = ClassIdentifier<T>::getIdentifier()->fabricate(); |
---|
50 | delete temp; |
---|
51 | ClassIdentifier<T>::getIdentifier()->stopCreatingHierarchy(); |
---|
52 | |
---|
53 | return true; |
---|
54 | } |
---|
55 | |
---|
56 | /** |
---|
57 | @brief Creates and returns a new object of class T. |
---|
58 | @return The new object |
---|
59 | */ |
---|
60 | template <class T> |
---|
61 | BaseObject* ClassFactory<T>::fabricate() |
---|
62 | { |
---|
63 | return ClassFactory<T>::createNewObject(); |
---|
64 | } |
---|
65 | |
---|
66 | /** |
---|
67 | @brief Creates and returns a new object of class T; this is a wrapper for the new operator. |
---|
68 | @return The new object |
---|
69 | */ |
---|
70 | template <class T> |
---|
71 | T* ClassFactory<T>::createNewObject() |
---|
72 | { |
---|
73 | return new T; |
---|
74 | } |
---|
75 | } |
---|
76 | |
---|
77 | #endif |
---|