Factory mode

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 AnimalFactoryGet(){
		static AnimalFactory instance;
		return &instance;
	}
	
	void Register(const QStringanimalName,CreateAnimalFn pfnCreate)
	{
		m_factoryMap[animalName] = pfnCreate();
	}
	IAnimalGreateAnimal(const QStringanimalName){
		FactoryMap::const_iterator itm_factoryMap.find(animalName);
		if(it != m_factoryMap.end())
			return it.value();
		return NULL;
	}
 
};
 
int main(int argc,char** argv){
	QApplication app(argc,argv);
	
	IAnimalpHorse = AnimalFactory::Get()->GreateAnimal("Horse");
 
	pHorse->Speak();
 
	return app.exec();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值