Factory Method模式示例(使用Loki类库)

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

#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];

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航