Shape.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();
};
Shape.cpp
#include "Shape.h"
#include "DynBase.h"
#include <iostream>
using namespace std;
void Circle::Draw() {
cout << "Circle::Draw() ..." << endl;
}
Circle::~Circle() noexcept {
cout << "Circle::~Circle() ..." << endl;
}
void Square::Draw() {
cout << "Square::Draw() ..." << endl;
}
Square::~Square() noexcept {
cout << "Square::~Square() ..." << endl;
}
void Rectangle::Draw() {
cout << "Rectangle::Draw() ..." << endl;
}
Rectangle::~Rectangle() noexcept {
cout << "Rectangle::~Rectangle() ..." << endl;
}
REGISTER_CLASS(Circle);
REGISTER_CLASS(Square);
REGISTER_CLASS(Rectangle);
DynBase.h
#include <map>
#include <string>
using namespace std;
typedef void* (*CREATE_FUNC)();
class DynObjectFactory
{
public:
static void* CreateObject(const string& name);
static void RegisterTo_mapCls_(const string& name, CREATE_FUNC func);
private:
static map<string, CREATE_FUNC> mapCls_;
};
class Register
{
public:
Register(const string& name, CREATE_FUNC 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)
DynBase.cpp
#include "DynBase.h"
map<string, CREATE_FUNC> DynObjectFactory::mapCls_;
void* DynObjectFactory::CreateObject(const string& name)
{
map<string, CREATE_FUNC>::const_iterator it;
it = mapCls_.find(name);
if (it == mapCls_.end())
{
return nullptr;
}
else
{
return it->second();
}
}
void DynObjectFactory::RegisterTo_mapCls_(const string& name, CREATE_FUNC func)
{
mapCls_[name] = func;
}
Register::Register(const std::string &name, CREATE_FUNC func) {
DynObjectFactory::RegisterTo_mapCls_(name, func);
}
main.cpp
#include <iostream>
using namespace std;
#include "Shape.h"
#include "DynBase.h"
#include <vector>
void DrawAllShapes(const vector<Shape*>& v)
{
vector<Shape*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
(*it)->Draw();
}
}
void DelAllShapes(const vector<Shape*>& v)
{
vector<Shape*>::const_iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
delete (*it);
}
}
int main() {
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);
DelAllShapes(v);
return 0;
}
输出:
Circle::Draw() ...
Square::Draw() ...
Rectangle::Draw() ...
Circle::~Circle() ...
Square::~Square() ...
Rectangle::~Rectangle() ...
这边主要是记录的通过宏定义注册的方式来动态的创建类,这个写法第一次见,比较新奇,值得记录。