KASKADE 7 development version
factory.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2002-2011 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef FACTORY_HH
14#define FACTORY_HH
15
16#include <cassert>
17#include <map>
18#include <memory>
19#include <string>
20
22
23namespace Kaskade
24{
29 template <class Product>
30 struct Creator
31 {
32 typedef int Argument;
33
34 std::unique_ptr<Product> operator()(Argument /* dummy */) const
35 {
36 return new Product;
37 }
38
39 template <class Key>
40 static std::string const& lookupFailureHint(Key const& /* ignored */)
41 {
42 static std::string msg = "Key not registered.";
43 return msg;
44 }
45 };
46
47
57 template <class K, class P>
58 class Factory
59 {
60 typedef std::map<K,Creator<P> const*> Map;
61
62 public:
63 typedef K Key;
64 typedef P Product;
65
66
67 static std::unique_ptr<Product> create(Key key, typename Creator<Product>::Argument arg)
68 {
69 return makeProduct(map().find(key),Creator<Product>::lookupFailureHint(key),arg);
70 }
71
72 static std::unique_ptr<Product> createAny(typename Creator<Product>::Argument arg)
73 {
74 return makeProduct(begin(map()),"no key registered",arg);
75 }
76
77
78
86 static void plugin(Key key, Creator<Product> const* creator)
87 {
88 map()[key] = creator;
89 }
90
91
92 private:
93
94 static std::unique_ptr<Product> makeProduct(typename Map::const_iterator i,
95 std::string message,
96 typename Creator<Product>::Argument arg)
97 {
98 if (i==map().end())
99 throw(LookupException(message,__FILE__,__LINE__));
100
101 return i->second->create(arg);
102 }
103
104 static Map& map()
105 {
106 static Map m; // this realizes a singleton
107 return m;
108 }
109 };
110
111} // namespace Kaskade
112#endif
A pluggable factory.
Definition: factory.hh:59
static std::unique_ptr< Product > create(Key key, typename Creator< Product >::Argument arg)
Definition: factory.hh:67
static std::unique_ptr< Product > createAny(typename Creator< Product >::Argument arg)
Definition: factory.hh:72
static void plugin(Key key, Creator< Product > const *creator)
Registers a creator for creation of Product objects with the given.
Definition: factory.hh:86
An exception that can be thrown whenever a key lookup fails.
Abstract base class of creators that can be registered at the pluggable factory.
Definition: factory.hh:31
std::unique_ptr< Product > operator()(Argument) const
Definition: factory.hh:34
static std::string const & lookupFailureHint(Key const &)
Definition: factory.hh:40