File indexing completed on 2024-05-12 04:04:32

0001 /*
0002     Copyright 2010 Stefan Majewsky <majewsky@gmx.net>
0003 
0004     This program is free software; you can redistribute it and/or modify
0005     it under the terms of the GNU General Public License as published by
0006     the Free Software Foundation; either version 2 of the License, or
0007     (at your option) any later version.
0008 
0009     This program is distributed in the hope that it will be useful,
0010     but WITHOUT ANY WARRANTY; without even the implied warranty of
0011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0012     GNU General Public License for more details.
0013 
0014     You should have received a copy of the GNU General Public License
0015     along with this program; if not, write to the Free Software
0016     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
0017 */
0018 
0019 #ifndef KOLF_ITEMFACTORY_H
0020 #define KOLF_ITEMFACTORY_H
0021 
0022 #include <QGraphicsItem>
0023 class b2World;
0024 
0025 namespace Kolf
0026 {
0027     struct ItemMetadata
0028     {
0029         QString identifier, name;
0030         bool addOnNewHole;
0031     };
0032 
0033     //This class registers maps identifiers and other metadata to QGraphicsItem subclasses, and is able to create item instances as needed.
0034     class ItemFactory
0035     {
0036         public:
0037             QList<Kolf::ItemMetadata> knownTypes() const;
0038             QGraphicsItem* createInstance(const QString& identifier, QGraphicsItem* parent, b2World* world) const;
0039 
0040             template<typename T> void registerType(const QString& identifier, const QString& name, bool addOnNewHole = false)
0041             {
0042                 const Kolf::ItemMetadata metadata = { identifier, name, addOnNewHole };
0043                 registerType(metadata, &Kolf::ItemFactory::create<T>);
0044             }
0045         private:
0046             typedef QGraphicsItem* (*ItemCreator)(QGraphicsItem* parent, b2World* world);
0047             void registerType(const Kolf::ItemMetadata& metadata, ItemCreator creator);
0048             template<typename T> static QGraphicsItem* create(QGraphicsItem* parent, b2World* world)
0049             {
0050                 return new T(parent, world);
0051             }
0052         private:
0053             typedef QPair<Kolf::ItemMetadata, ItemCreator> Entry;
0054             QList<Entry> m_entries;
0055     };
0056 }
0057 
0058 #endif // KOLF_ITEMFACTORY_H