【C++设计模式】用简单工厂模式实现按汽车重量输出汽车类型

2023年8月24日,周四凌晨


cpp 复制代码
#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;
	}
	
}
相关推荐
NiNi_suanfa1 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
信奥胡老师2 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺2 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
开心香辣派小星2 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
star _chen2 小时前
C++实现完美洗牌算法
开发语言·c++·算法
繁星星繁3 小时前
【C++】脚手架学习笔记 gflags与 gtest
c++·笔记·学习
路痴楷4 小时前
无法定位程序输入点问题
c++·qt·visual studio
Source.Liu4 小时前
【LibreCAD】 RS_Units 类完整解析
c++·qt·rust
我是一棵无人问荆的小草5 小时前
编码演变史
开发语言·c++
potato_may5 小时前
CC++ 内存管理 —— 程序的“五脏六腑”在哪里?
c语言·开发语言·数据结构·c++·内存·内存管理