1 | /* |
2 | Copyright 2010 Stefan Majewsky <majewsky@gmx.net> |
3 | |
4 | This program is free software; you can redistribute it and/or modify |
5 | it under the terms of the GNU General Public License as published by |
6 | the Free Software Foundation; either version 2 of the License, or |
7 | (at your option) any later version. |
8 | |
9 | This program is distributed in the hope that it will be useful, |
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 | GNU General Public License for more details. |
13 | |
14 | You should have received a copy of the GNU General Public License |
15 | along with this program; if not, write to the Free Software |
16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
17 | */ |
18 | |
19 | #ifndef KOLF_ITEMFACTORY_H |
20 | #define KOLF_ITEMFACTORY_H |
21 | |
22 | #include <QGraphicsItem> |
23 | class b2World; |
24 | |
25 | namespace Kolf |
26 | { |
27 | struct ItemMetadata |
28 | { |
29 | QString identifier, name; |
30 | bool addOnNewHole; |
31 | }; |
32 | |
33 | //This class registers maps identifiers and other metadata to QGraphicsItem subclasses, and is able to create item instances as needed. |
34 | class ItemFactory |
35 | { |
36 | public: |
37 | QList<Kolf::ItemMetadata> knownTypes() const; |
38 | QGraphicsItem* createInstance(const QString& identifier, QGraphicsItem* parent, b2World* world) const; |
39 | |
40 | template<typename T> void registerType(const QString& identifier, const QString& name, bool addOnNewHole = false) |
41 | { |
42 | const Kolf::ItemMetadata metadata = { identifier, name, addOnNewHole }; |
43 | registerType(metadata, &Kolf::ItemFactory::create<T>); |
44 | } |
45 | private: |
46 | typedef QGraphicsItem* (*ItemCreator)(QGraphicsItem* parent, b2World* world); |
47 | void registerType(const Kolf::ItemMetadata& metadata, ItemCreator creator); |
48 | template<typename T> static QGraphicsItem* create(QGraphicsItem* parent, b2World* world) |
49 | { |
50 | return new T(parent, world); |
51 | } |
52 | private: |
53 | typedef QPair<Kolf::ItemMetadata, ItemCreator> Entry; |
54 | QList<Entry> m_entries; |
55 | }; |
56 | } |
57 | |
58 | #endif // KOLF_ITEMFACTORY_H |
59 | |