KASKADE 7 development version
Loading...
Searching...
No Matches
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{
31 template <class Product>
32 struct Creator
33 {
34 typedef int Argument;
35
36 std::unique_ptr<Product> operator()(Argument /* dummy */) const
37 {
38 return new Product;
39 }
40
41 template <class Key>
42 static std::string const& lookupFailureHint(Key const& /* ignored */)
43 {
44 static std::string msg = "Key not registered.";
45 return msg;
46 }
47 };
48
49
59 template <class K, class P>
60 class Factory
61 {
62 typedef std::map<K,Creator<P> const*> Map;
63
64 public:
65 typedef K Key;
66 typedef P Product;
67
68
69 static std::unique_ptr<Product> create(Key key, typename Creator<Product>::Argument arg)
70 {
71 return makeProduct(map().find(key),Creator<Product>::lookupFailureHint(key),arg);
72 }
73
74 static std::unique_ptr<Product> createAny(typename Creator<Product>::Argument arg)
75 {
76 return makeProduct(begin(map()),"no key registered",arg);
77 }
78
79
80
90 static void plugin(Key key, Creator<Product> const* creator)
91 {
92 map()[key] = creator;
93 }
94
95
96 private:
97
98 static std::unique_ptr<Product> makeProduct(typename Map::const_iterator i,
99 std::string message,
100 typename Creator<Product>::Argument arg)
101 {
102 if (i==map().end())
103 throw(LookupException(message,__FILE__,__LINE__));
104
105 return i->second->create(arg);
106 }
107
108 static Map& map()
109 {
110 static Map m; // this realizes a singleton
111 return m;
112 }
113 };
114
115} // namespace Kaskade
116#endif
A pluggable factory.
Definition factory.hh:61
static std::unique_ptr< Product > create(Key key, typename Creator< Product >::Argument arg)
Definition factory.hh:69
static std::unique_ptr< Product > createAny(typename Creator< Product >::Argument arg)
Definition factory.hh:74
static void plugin(Key key, Creator< Product > const *creator)
Registers a creator for creation of Product objects with the given.
Definition factory.hh:90
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:33
std::unique_ptr< Product > operator()(Argument) const
Definition factory.hh:36
static std::string const & lookupFailureHint(Key const &)
Definition factory.hh:42