Factory Method Mode example (using the Loki class library)

xiaoxiao2021-03-06  50

#include

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 us_loki

#ifndef use_loki // Traditional Method

Class shapefactory {

PUBLIC:

Static ShapeFactory & Instance () {

STATIC shapefactory installation;

Return Instance;

}

Shape * creteObject (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 Singletonhold > ShapeFactory;

Shape * Createline () {return new line;}

Static const bool letryg = shapefactory :: instance (). register (shape_line, createline);

Shape * createpolygon () {return new polygon;

STATIC const boilgonreg = 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];

}

}

转载请注明原文地址:https://www.9cbs.com/read-80845.html

New Post(0)