应用实例
用户需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个汽车里面的具体实现细节
代码实例
创建一个接口
class Shape{
public:
virtual void draw() = 0;
}
创建实现接口的实体类
class Squre: public Shape{
public:
void draw(){
cout<<"Image that it drawn a Squre."<<endl;
}
}
class Rectangle: public Shape{
public:
void draw(){
cout<<"Image that it drawn a Rectangle."<<endl;
}
}
class Circle: public Shape{
public:
void draw(){
cout<<"Image that it drawn a Circle."<<endl;
}
}
创建一个工厂,生成给定信息的实体类的对象
class ShapeFactory{
Shape getShape(string shapetype){
if(ShapeType == "Circle") reutrn new Circle();
else if(ShapeType == "Rectangle") reutrn new Rectangle();
else if(ShapeType == "Squre") reutrn new Squre();
else return nullptr;
}
}
使用工厂传递信息获取实体类的对象
void FactoryPattrenDemo(){
ShapeFactory ShapeF = new ShapeFactory();
Shape s1, s2, s3;
s1 = ShapeF.getShape("Circle");
s1.draw();
s2 = ShapeF.getShape("Rectangle");
s2.draw();
s3 = ShapeF.getShape("Squre");
s3.draw();
return;
}
int main(){
FactoryPattrenDemo();
return 0;
}
输出:
Image that it drawn a Circle.
Image that it drawn a Rectangle.
Image that it drawn a Squre.