您的位置:首页 > 其它

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];
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: