2023年8月24日,周四凌晨
#include<iostream>
class CarType{
public:
virtual std::string getType()=0;
};
class MiniCar:public CarType{
public:
std::string getType() override{
return "小型车";
};
};
class MidSizeCar:public CarType{
public:
std::string getType() override{
return "中型车";
};
};
class HeavyCar:public CarType{
public:
std::string getType() override{
return "重型车";
};
};
class CarTypeFactory{
public:
CarType* createCarType(int weight){
if(weight<5){
return new MiniCar();
}else if(weight<10){
return new MidSizeCar();
}else{
return new HeavyCar();
}
return nullptr;
}
};
int main(){
int weight;
CarType *carType;
CarTypeFactory *factory=new CarTypeFactory();
while(1){
std::cout<<"请输入汽车的重量(吨):";
std::cin>>weight;
carType=factory->createCarType(weight);
std::cout<<carType->getType()<<std::endl;
}
}
文章来源:https://www.toymoban.com/news/detail-671276.html
文章来源地址https://www.toymoban.com/news/detail-671276.html
到了这里,关于【C++设计模式】用简单工厂模式实现按汽车重量输出汽车类型的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!