Factory Method模式示例(使用Loki类库)
2004-12-14 16:08
615 查看
[code]#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]; } }
相关文章推荐
- Visitor模式示例(使用Loki类库)
- 在项目中使用设计模式思想——Abstract Factory、Factory Method、Singleton和Strategy模式的使用(上)
- 设计模式示例一 Factory Method(工厂方法)
- 在项目中使用设计模式思想——Abstract Factory、Factory Method、Singleton和Strategy模式的使用(上)
- Abstract Factory模式示例(使用Locki类库)
- 设计模式示例一 Factory Method(工厂方法)
- factory method模式使用之前
- 设计模式 (5)——工厂方法模式(Factory Method,创建型)
- C#设计模式之Factory Method
- VB.net设计模式之工厂方法,抽象工厂方法(Factory Method Pattern,Abstract Factory Method Pattern)
- C#设计模式_创建型_FactoryMethod模式(learn from Lijianzhong & others)
- 1.Factory Method (工厂方法模式、虚构造子模式、多态工厂模式)
- Factory Method 模式
- Python使用设计模式中的责任链模式与迭代器模式的示例
- 设计模式之(Factory method)工厂方法模式
- 设计模式之工厂方法(factory method)
- C#设计模式——工厂方法模式(Factory Method)
- Java使用设计模式中迭代器模式构建项目的代码结构示例
- 1.3 Factory Method(工厂方法) -- 对象创建型模式
- 设计模式之一 工厂方法模式(Factory Method)