想了很久,结合c++设计新思维的方法,大家这种设计会有什么问题?
-----------IShape.h-----------------
class IShape
{
public:
IShape()
{
printf("\n IShape\n");
}
virtual ~IShape()
{
printf("\n ~IShape\n");
}
virtual void Draw() = 0;
};
typedef const char* ShapeType;
typedef IShape* (*Creator)();
------------ShapeFactory.h--------------------
class ShapeFactory {
public:
static ShapeFactory& Instance() {
static ShapeFactory instance;
return instance;
}
IShape* Create(ShapeType shapeType);
bool RegisterShape(ShapeType shapeType, Creator creator);
private:
ShapeFactory() {}
std::map<ShapeType, Creator> shapeCreators;
};
------------ShapeFactory.cpp--------------------
#include "CFactory.h"
IShape* ShapeFactory::Create(ShapeType shapeType) {
Creator creator = shapeCreators.find( shapeType )->second;
if ( creator == NULL )
{
return NULL;
}
return creator();
}
bool ShapeFactory::RegisterShape( ShapeType shapeType, Creator creator ) {
map<ShapeType, Creator>::iterator iter;
iter = shapeCreators.find(shapeType);
if(iter != shapeCreators.end())
{
return false;
} else {
shapeCreators[shapeType] = creator;
return true;
}
}
------------CCircle .h--------------------
#include<stdio.h>
#include "IShape.h"
#include "CFactory.h"
class CCircle : public IShape
{
public:
CCircle()
{
printf("\n CCircle\n");
}
virtual ~CCircle()
{
printf("\n ~CCircle\n");
}
virtual void Draw();
};
------------CCircle .cpp--------------------
#include "CCircle.h"
IShape* Create() { return new CCircle(); }
static const bool RegisterShape__ = ShapeFactory::Instance().RegisterShape( "CCircle", Create);
void CCircle::Draw()
{
printf("\n CCircle::Draw\n");
}
------------main.cpp--------------------
#include<stdio.h>
#include"CFactory.h"
#include "IShape.h"
int main() {
IShape* line = ShapeFactory::Instance().Create("CCircle");
line->Draw();
return 0;
}
有点小小的兴奋,大家积极发言哟!!!
主要参考: http://blog.csdn.net/jicao/archive/2006/07/01/861343.aspx
http://blog.csdn.net/hjsunj/archive/2008/01/07/2028597.aspx
《c++设计新思维》