MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
factory.hpp
1 /*
2  Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; see the file COPYING. If not, write to the
15  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
16  MA 02110-1301 USA.
17 */
18 
19 /* The factory header defines an Object Factory, used by SSL message and
20  * handshake types.
21  *
22  * See Desgin Pattern in GoF and Alexandrescu's chapter in Modern C++ Design,
23  * page 208
24  */
25 
26 
27 
28 #ifndef yaSSL_FACTORY_HPP
29 #define yaSSL_FACTORY_HPP
30 
31 #include STL_VECTOR_FILE
32 #include STL_PAIR_FILE
33 
34 
35 namespace STL = STL_NAMESPACE;
36 
37 
38 
39 
40 
41 namespace yaSSL {
42 
43 
44 // Factory uses its callback map to create objects by id,
45 // returning an abstract base pointer
46 template<class AbstractProduct,
47  typename IdentifierType = int,
48  typename ProductCreator = AbstractProduct* (*)()
49  >
50 class Factory {
51  typedef STL::pair<IdentifierType, ProductCreator> CallBack;
52  typedef STL::vector<CallBack> CallBackVector;
53 
54  CallBackVector callbacks_;
55 public:
56  // pass function pointer to register all callbacks upon creation
57  explicit Factory(void (*init)(Factory<AbstractProduct, IdentifierType,
58  ProductCreator>&))
59  {
60  init(*this);
61  }
62 
63  // reserve place in vector before registering, used by init funcion
64  void Reserve(size_t sz)
65  {
66  callbacks_.reserve(sz);
67  }
68 
69  // register callback
70  void Register(const IdentifierType& id, ProductCreator pc)
71  {
72  callbacks_.push_back(STL::make_pair(id, pc));
73  }
74 
75  // THE Creator, returns a new object of the proper type or 0
76  AbstractProduct* CreateObject(const IdentifierType& id) const
77  {
78  typedef typename STL::vector<CallBack>::const_iterator cIter;
79 
80  cIter first = callbacks_.begin();
81  cIter last = callbacks_.end();
82 
83  while (first != last) {
84  if (first->first == id)
85  break;
86  ++first;
87  }
88 
89  if (first == callbacks_.end())
90  return 0;
91  return (first->second)();
92  }
93 private:
94  Factory(const Factory&); // hide copy
95  Factory& operator=(const Factory&); // and assign
96 };
97 
98 
99 } // naemspace
100 
101 #endif // yaSSL_FACTORY_HPP