OLD | NEW |
| (Empty) |
1 // Copyright 2007-2009 Google Inc. | |
2 // | |
3 // Licensed under the Apache License, Version 2.0 (the "License"); | |
4 // you may not use this file except in compliance with the License. | |
5 // You may obtain a copy of the License at | |
6 // | |
7 // http://www.apache.org/licenses/LICENSE-2.0 | |
8 // | |
9 // Unless required by applicable law or agreed to in writing, software | |
10 // distributed under the License is distributed on an "AS IS" BASIS, | |
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 // See the License for the specific language governing permissions and | |
13 // limitations under the License. | |
14 // ======================================================================== | |
15 | |
16 #ifndef OMAHA_BASE_OBJECT_FACTORY_H_ | |
17 #define OMAHA_BASE_OBJECT_FACTORY_H_ | |
18 | |
19 #include <map> | |
20 | |
21 namespace omaha { | |
22 | |
23 // Factory creates instances of objects based on a unique type id. | |
24 // | |
25 // AbstractProduct - base class of the product hierarchy. | |
26 // TypeId - type id for each type in the hierarchy. | |
27 // ProductCreator - callable entity to create objects. | |
28 | |
29 template <class AbstractProduct, | |
30 typename TypeId, | |
31 typename ProductCreator = AbstractProduct* (*)()> | |
32 class Factory { | |
33 public: | |
34 Factory() {} | |
35 | |
36 // Registers a creator for the type id. Returns true if the creator has | |
37 // been registered succesfully. | |
38 bool Register(const TypeId& id, ProductCreator creator) { | |
39 return id_to_creators_.insert(Map::value_type(id, creator)).second; | |
40 } | |
41 | |
42 // Unregisters a type id. | |
43 bool Unregister(const TypeId& id) { | |
44 return id_to_creators_.erase(id) == 1; | |
45 } | |
46 | |
47 // Creates an instance of the abstract product. | |
48 AbstractProduct* CreateObject(const TypeId& id) const { | |
49 typename Map::const_iterator it = id_to_creators_.find(id); | |
50 if (it != id_to_creators_.end()) { | |
51 return (it->second)(); | |
52 } else { | |
53 return NULL; | |
54 } | |
55 } | |
56 | |
57 private: | |
58 typedef std::map<TypeId, ProductCreator> Map; | |
59 Map id_to_creators_; | |
60 | |
61 DISALLOW_EVIL_CONSTRUCTORS(Factory); | |
62 }; | |
63 | |
64 } // namespace omaha | |
65 | |
66 #endif // OMAHA_BASE_OBJECT_FACTORY_H_ | |
67 | |
OLD | NEW |