Recently,I find a post about the Factory Mode.I like this and learn some knowledge.
#include <QDebug> #include <QMap> #include <QApplication> class IAnimal { public: virtual int GetNumberOfLegs() const = 0; virtual void Speak() = 0; virtual void Free() = 0; }; typedef IAnimal* (__stdcall *CreateAnimalFn)(void); class Cat : public IAnimal { public: int GetNumberOfLegs() const { return 4; } void Speak() { qDebug() << "Meow"; } void Free() { delete this; } static IAnimal * __stdcall Create() { return new Cat(); } }; class Dog : public IAnimal { public: int GetNumberOfLegs() const { return 4; } void Speak() { qDebug() << "Woof"; } void Free() { delete this; } static IAnimal * __stdcall Create() { return new Dog(); } }; class Spider : public IAnimal // Yeah it isn’t really an animal… { public: int GetNumberOfLegs() const { return 8; } void Speak() { qDebug() << "Spider"; } void Free() { delete this; } static IAnimal * __stdcall Create() { return new Spider(); } }; class Horse : public IAnimal { public: int GetNumberOfLegs() const { return 4; } void Speak() { qDebug() << "A horse is a horse, of course, of course."; } void Free() { delete this; } static IAnimal * __stdcall Create() { return new Horse(); } }; /*! * \class AnimalFactory * \brief * \note * \author 王东江 * \version 1.0 * \date 四月 2015 * Contact: cmm_djtec@163.com * */ class AnimalFactory { private: AnimalFactory() { Register("Horse", &Horse::Create); Register("Cat",&Cat::Create); Register("Dog",&Dog::Create); Register("Spider", &Spider::Create); } AnimalFactory(const AnimalFactory&){} AnimalFactory &operator=(const AnimalFactory& ){return *this;} typedef QMap<QString,IAnimal*> FactoryMap; FactoryMap m_factoryMap; public: ~AnimalFactory(){m_factoryMap.clear();} static AnimalFactory* Get(){ static AnimalFactory instance; return &instance; } void Register(const QString& animalName,CreateAnimalFn pfnCreate) { m_factoryMap[animalName] = pfnCreate(); } IAnimal* GreateAnimal(const QString& animalName){ FactoryMap::const_iterator it= m_factoryMap.find(animalName); if(it != m_factoryMap.end()) return it.value(); return NULL; } }; int main(int argc,char** argv){ QApplication app(argc,argv); IAnimal* pHorse = AnimalFactory::Get()->GreateAnimal("Horse"); pHorse->Speak(); return app.exec(); }