看了MFC中的动态创建对象后,感觉动态创建对象算是一种技术吧,理论上说算是一种设计模式。其实创建的原理很明了,把对象的类别名称和其构造函数用容器记录下来,在需要的时候给出创建类别查找容器即可创建对象。当然这里我们需要自定义一个全局的函数指针用来指向类别的构造函数。在这里我们使用类工厂模式,在泪工厂中我们定义一个通用构造函数,将函数指针指向它。下面是参考一位网友思路来整理和摸索的代码:
//通用的函数指针
typedef void *(*CREATE_FUNC)();
//创建类的工厂类
class DynObjectFactory { public: static void *CreateObject( const string &name) { map<string, CREATE_FUNC>::const_iterator it; it = mapCls_.find(name); if (it == mapCls_.end()) return 0; else return it->second(); //func(); } static void Register( const string &name, CREATE_FUNC func) { mapCls_[name] = func; } private: static map<string, CREATE_FUNC> mapCls_; }; //头文件被包含多次,也只定义一次mapCls_; __declspec(selectany) map<string, CREATE_FUNC> DynObjectFactory::mapCls_; class Register { public: Register( const string &name, CREATE_FUNC func) { DynObjectFactory::Register(name, func); } }; #define REGISTER_CLASS(class_name) class class_name##Register { public: static void* NewInstance() { return new class_name; } private: static Register reg_; }; Register class_name##Register::reg_(#class_name, class_name##Register::NewInstance) //CircleRegister
//下面是测试类 *.h
class Shape
{
public:
virtual void Draw() = 0;
virtual ~Shape() {}
};
class Circle : public Shape
{
public:
void Draw();
~Circle();
};
class Square : public Shape
{
public:
void Draw();
~Square();
};
class Rectangle : public Shape
{
public:
void Draw();
~Rectangle();
};
//*.cpp
void Circle::Draw()
{
cout << "Circle::Draw() ..." << endl;
}
Circle::~Circle()
{
cout << "~Circle ..." << endl;
}
void Square::Draw()
{
cout << "Square::Draw() ..." << endl;
}
Square::~Square()
{
cout << "~Square ..." << endl;
}
void Rectangle::Draw()
{
cout << "Rectangle::Draw() ..." << endl;
}
Rectangle::~Rectangle()
{
cout << "~Rectangle ..." << endl;
}
REGISTER_CLASS(Circle);
REGISTER_CLASS(Square);
REGISTER_CLASS(Rectangle);
//main.cpp
void DrawAllShapes( const vector<Shape *> &v)
{
vector<Shape *>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->Draw();
}
}
void DeleteAllShapes( const vector<Shape *> &v)
{
vector<Shape *>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
delete(*it);
}
}
int main( void)
{
vector<Shape *> v;
Shape *ps;
ps = static_cast<Shape *>(DynObjectFactory::CreateObject( "Circle"));
v.push_back(ps);
ps = static_cast<Shape *>(DynObjectFactory::CreateObject( "Square"));
v.push_back(ps);
ps = static_cast<Shape *>(DynObjectFactory::CreateObject( "Rectangle"));
v.push_back(ps);
DrawAllShapes(v);
DeleteAllShapes(v);
return 0;
}
本文出自 “GDT解说” 博客,请务必保留此出处http://844133395.blog.51cto.com/3483632/1722559
原文地址:http://844133395.blog.51cto.com/3483632/1722559