我正在阅读关于创建型设计模式的内容,但是在 Factory、Abstract Factory 和 Factory method 之间搞混了自己。
下面是一段代码片段。请问这是哪个模式?如果可能的话,有什么改动可以使它符合其他模式的要求吗?
#include "iostream.h"
#define QUIT 2
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() {
cout << "circle : draw" << endl;
}
};
class Square : public Shape {
public:
void draw() {
cout << "square : draw" << endl;
}
};
class Factory {
public:
virtual Shape* createInstance(int id) = 0;
};
class SimpleShapeFactory : public Factory {
public:
Shape* createInstance( int id) {
if(id == 0)
return new Circle;
else if(id == 1)
return new Square;
else
return new Circle; //as a default
}
};
int main() {
Factory* factory = new SimpleShapeFactory();
int choice = 0;
Shape* shape;
do
{
cout<<"\n 0. Circle";
cout<<"\n 1. Square";
cout<<"\n 2. Quit";
cout<<"\n Enter your choice : ";
cin>>choice;
if(choice == QUIT)
break;
shape = factory->createInstance(choice);
shape->draw();
} while (choice !=QUIT);
}