Fix coverity #29357
[supertux.git] / src / supertux / object_factory.hpp
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
25 #include "supertux/direction.hpp"
26 #include "supertux/game_object_ptr.hpp"
27 #include "util/reader_fwd.hpp"
28
29 class Vector;
30 class GameObject;
31
32 class AbstractObjectFactory
33 {
34 public:
35   virtual ~AbstractObjectFactory()
36   { }
37
38   /** Creates a new gameobject from a lisp node.
39    * Remember to delete the objects later
40    */
41   virtual GameObjectPtr create(const Reader& reader) = 0;
42 };
43
44 template<class C>
45 class ConcreteObjectFactory : public AbstractObjectFactory
46 {
47 public:
48   ConcreteObjectFactory() {}
49   ~ConcreteObjectFactory() {}
50
51   GameObjectPtr create(const Reader& reader)
52   {
53     return std::make_shared<C>(reader);
54   }
55 };
56
57 class ObjectFactory
58 {
59 public:
60   static ObjectFactory& instance();
61
62 private:
63   typedef std::map<std::string, std::unique_ptr<AbstractObjectFactory> > Factories;
64   Factories factories;
65
66 public:
67   ObjectFactory();
68   ~ObjectFactory();
69
70   GameObjectPtr create(const std::string& name, const Reader& reader);
71   GameObjectPtr create(const std::string& name, const Vector& pos, const Direction dir = AUTO);
72
73 private:
74   template<class C>
75   void add_factory(const char* name)
76   {
77     assert(factories.find(name) == factories.end());
78     factories[name] = std::unique_ptr<AbstractObjectFactory>(new ConcreteObjectFactory<C>());
79   }
80   void init_factories();
81 };
82
83 #endif
84
85 /* EOF */