#include <iostream> using namespace std; // Abstract Shape struct Shape { virtual ~Shape(){} }; enum {SHAPE_LINE = 1, SHAPE_POLYGON = 3, SHAPE_CIRCLE = 5}; // Concrete Shapes: Line, Polygon and Circle struct Line : public Shape { Line() { cout << "Line::ctor" << endl; } }; struct Polygon : public Shape { Polygon() { cout << "Polygon::ctor" << endl; } }; struct Circle : public Shape { Circle() { cout << "Circle::ctor" << endl; } }; // Comment out the line below if you want to use traditional method #define USE_LOKI #ifndef USE_LOKI // traditional method class ShapeFactory { public: static ShapeFactory& Instance() { static ShapeFactory instance; return instance; } Shape* CreateObject(int id){ switch(id) { case SHAPE_LINE: return new Line; case SHAPE_POLYGON: return new Polygon; case SHAPE_CIRCLE: return new Circle; default: throw "Unknown Type"; } } protected: ShapeFactory() {} private: ShapeFactory(const ShapeFactory&); ShapeFactory& operator=(const ShapeFactory&); }; #else // Loki method #include "Factory.h" #include "Singleton.h" using namespace Loki; typedef SingletonHolder<Factory<Shape, int> > ShapeFactory; Shape* CreateLine(){return new Line;} static const bool lineReg = ShapeFactory::Instance().Register(SHAPE_LINE, CreateLine); Shape* CreatePolygon(){return new Polygon;} static const bool polygonReg = ShapeFactory::Instance().Register(SHAPE_POLYGON, CreatePolygon); Shape* CreateCircle(){return new Circle;} static const bool circleReg = ShapeFactory::Instance().Register(SHAPE_CIRCLE, CreateCircle); #endif void main() { int id[3] = {SHAPE_LINE, SHAPE_POLYGON, SHAPE_CIRCLE}; Shape* pShapes[3]; for(int i = 0; i < 3; i++){ pShapes[i] = ShapeFactory::Instance().CreateObject(id[i]); delete pShapes[i]; } }
本文地址:http://com.8s8s.com/it/it24426.htm