看了MFC中的動態(tài)創(chuàng)建對象后,感覺動態(tài)創(chuàng)建對象算是一種技術(shù)吧,理論上說算是一種設(shè)計(jì)模式,
C++ 類工廠實(shí)現(xiàn)動態(tài)對象創(chuàng)建
。其實(shí)創(chuàng)建的原理很明了,把對象的類別名稱和其構(gòu)造函數(shù)用容器記錄下來,在需要的時(shí)候給出創(chuàng)建類別查找容器即可創(chuàng)建對象。當(dāng)然這里我們需要自定義一個(gè)全局的函數(shù)指針用來指向類別的構(gòu)造函數(shù)。在這里我們使用類工廠模式,在淚工廠中我們定義一個(gè)通用構(gòu)造函數(shù),將函數(shù)指針指向它。下面是參考一位網(wǎng)友思路來整理和摸索的代碼://通用的函數(shù)指針
typedef void *(*CREATE_FUNC)();
//創(chuàng)建類的工廠類
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
{
vector
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->Draw();
}
}
void DeleteAllShapes( const vector
{
vector
for (it = v.begin(); it != v.end(); ++it)
{
delete(*it);
}
}
int main( void)
{
vector
Shape *ps;
ps = static_cast
v.push_back(ps);
ps = static_cast
v.push_back(ps);
ps = static_cast
v.push_back(ps);
DrawAllShapes(v);
DeleteAllShapes(v);
return 0;
}