CUBRID Engine  latest
object_factory.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2008 Search Solution Corporation
3  * Copyright 2016 CUBRID Corporation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 /*
20  * object_factory.hpp
21  */
22 
23 #ifndef _OBJECT_FACTORY_HPP_
24 #define _OBJECT_FACTORY_HPP_
25 
26 #ident "$Id$"
27 
28 #include <cassert>
29 #include <functional>
30 #include <map>
31 
32 /*
33  * factory of objects:
34  * 'object_base' is the base class having derived classed 'object_type'
35  * each 'object_type' is identified by a value of 'object_key'
36  */
37 namespace cubbase
38 {
39  template <typename object_key, typename object_base> class factory
40  {
41  public:
42  template <typename object_type>
43  int register_creator (object_key k,
44  std::function <object_base*()> object_creator = default_creator <object_type>)
45  {
46  typename std::map<object_key, std::function <object_base*()>>::iterator it = m_creators_map.find (k);
47  if (it != m_creators_map.end ())
48  {
49  /* key already used */
50  assert (false);
51  return -1;
52  }
53 
54  m_creators_map[k] = object_creator;
55  return 0;
56  };
57 
58  object_base *create_object (object_key k)
59  {
60  typename std::map<object_key, std::function <object_base*()>>::iterator it = m_creators_map.find (k);
61  if (it == m_creators_map.end ())
62  {
63  return NULL;
64  }
65  return (it->second) ();
66  };
67 
68  private:
69  template <typename object_type>
70  static object_base *default_creator ()
71  {
72  return new object_type;
73  };
74 
75  std::map <object_key, std::function <object_base*()>> m_creators_map;
76  };
77 
78 } /* namespace cubbase */
79 
80 #endif /* _OBJECT_FACTORY_HPP_ */
#define assert(x)
std::map< object_key, std::function< object_base *()> > m_creators_map
#define NULL
Definition: freelistheap.h:34
static object_base * default_creator()
object_base * create_object(object_key k)
int register_creator(object_key k, std::function< object_base *()> object_creator=default_creator< object_type >)