模式意图:定义创建对象的接口,封装对象的创建;使具体化类的工作延迟到子类中。
主要解决:主要解决接口选择问题。
何时使用:在不同条件下创建不同实例。
步骤1:创建一个接口
class Shape {
public:
Shape();
virtual ~Shape() = 0;
virtual void draw() = 0;
}
步骤2:创建实现接口的实体类
class Rectangle:public Shape {
public:
Rectangle();
virtual ~Rectangle();
void draw() {
cout << "Rectangle draw method" << endl;
}
}
class Square:public Shape {
public:
Square();
virtual ~Square();
void draw() {
cout << "Square draw method" << endl;
}
}
class Circle:public Shape {
public:
Circle();
virtual ~Circle();
void draw() {
cout << "Circle draw method" << endl;
}
}
步骤3:创建一个工厂,生成基于给定信息的实体类对象
class ShapeFactory {
public:
ShapeFactory(){};
~ShapeFactory(){};
Shape getShape(String shapeType) {
if(shapeType == null){
return null;
}
if(shapeType == "CIRCLE") {
return new Circle();
} else if(shapeType == "RECTANGLE"){
return new Rectangle();
} else if(shapeType == "SQUARE"){
return new Square();
}
return null;
}
}
步骤4:使用该工厂,通过传递类型信息来获取实体类的对象
main() {
ShapeFactory shapeFactory = new ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//调用 Circle 的 draw 方法
shape1.draw();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}