1// SuperTux
2// Copyright (C) 2004 Ricardo Cruz <rick2@aeiou.pt>
3// Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4//
5// This program is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18#ifndef HEADER_SUPERTUX_SUPERTUX_OBJECT_FACTORY_HPP
19#define HEADER_SUPERTUX_SUPERTUX_OBJECT_FACTORY_HPP
20
21#include <assert.h>
22#include <map>
23#include <memory>
24#include <functional>
25
26#include "supertux/direction.hpp"
27
28class ReaderMapping;
29class Vector;
30class GameObject;
31
32class ObjectFactory
33{
34private:
35 typedef std::function<std::unique_ptr<GameObject> (const ReaderMapping&)> FactoryFunction;
36 typedef std::map<std::string, FactoryFunction> Factories;
37 Factories factories;
38
39public:
40 /** Will throw in case of creation failure, will never return nullptr */
41 std::unique_ptr<GameObject> create(const std::string& name, const ReaderMapping& reader) const;
42
43protected:
44 ObjectFactory();
45
46 void add_factory(const char* name, const FactoryFunction& func)
47 {
48 assert(factories.find(name) == factories.end());
49 factories[name] = func;
50 }
51
52 template<class C>
53 void add_factory(const char* name)
54 {
55 add_factory(name, [](const ReaderMapping& reader) {
56 return std::make_unique<C>(reader);
57 });
58 }
59};
60
61#endif
62
63/* EOF */
64