其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Factory Method模式示例(使用Loki类库)

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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



相关文章

相关软件