```
#include <QCoreApplication>
#include <iostream>
using namespace std;
#define REGIST_CLASS_2(className)\
class className##REGIST\
{\
public: \
className classnum;\
className##REGIST(){Factory::procudtion_list.insert(std::make_pair(classnum.GetId(), new className()));}\
};\
static className##REGIST className##GloableDeclare
class Analysis
{
public:
Analysis(){}
virtual ~Analysis(){}
virtual bool open() = 0;
virtual Analysis *Clone() = 0;
virtual int GetId(){return id;}
protected:
int id;
};
//工厂
class Factory
{
private:
Factory(){}
static Factory *m_factory;
public:
~Factory(){}
Analysis *Create(int num)
{
Analysis *analysis;
auto iter = procudtion_list.find(num);
if(iter != procudtion_list.end())
{
return iter->second->Clone();
}
else
{
cout << "not find product!" << endl;
}
}
static Factory *GetInstance()
{
if(m_factory == nullptr)
{
m_factory = new Factory();
}
return m_factory;
}
static void DestoryInstance()
{
if(m_factory != nullptr)
{
delete m_factory;
m_factory = NULL;
}
}
static std::map<int, Analysis*> procudtion_list;
};
Factory* Factory::m_factory = nullptr;
std::map<int, Analysis*> Factory::procudtion_list;
//产品1
class BagAnalysis : public Analysis
{
public:
BagAnalysis(){
this->id = 0;
}
BagAnalysis(BagAnalysis& other){
this->id = other.id;
}
virtual ~BagAnalysis(){}
virtual bool open()
{
cout << "chanpin 1 ok" << endl;
return true;
}
virtual Analysis *Clone(){
return new BagAnalysis(*this);
}
};
REGIST_CLASS_2(BagAnalysis);
//产品2
class My:public Analysis
{
public:
My(){
this->id = 1;
}
My(My &other){
this->id = other.id;
}
virtual bool open()
{
cout << "chanpin 2 ok" << endl;
return true;
}
virtual Analysis *Clone(){
return new My(*this);
}
};
REGIST_CLASS_2(My);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Factory *factory = Factory::GetInstance();
Analysis *a1 = factory->Create(0);
a1->open();
Factory::DestoryInstance();
return a.exec();
}
```
网友评论