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