【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;
	}
	
}
相关推荐
沐怡旸11 小时前
【穿越Effective C++】条款02:尽量以const, enum, inline替换#define
c++·面试
给大佬递杯卡布奇诺11 小时前
FFmpeg 基本API avcodec_alloc_context3函数内部调用流程分析
c++·ffmpeg·音视频
QT 小鲜肉11 小时前
【个人成长笔记】Qt 中 SkipEmptyParts 编译错误解决方案及版本兼容性指南
数据库·c++·笔记·qt·学习·学习方法
看到我,请让我去学习11 小时前
Qt 控件 QSS 样式大全(通用属性篇)
开发语言·c++·qt
筱砚.12 小时前
【STL——vector容器】
开发语言·c++
相偎12 小时前
用观察者模式通知UI刷新数据
c++
YBN娜13 小时前
设计模式-创建型设计模式
java·开发语言·设计模式
CoderCodingNo13 小时前
【GESP】C++四级真题 luogu-B4040 [GESP202409 四级] 黑白方块
开发语言·c++
小欣加油13 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
给大佬递杯卡布奇诺14 小时前
FFmpeg 基本API avio_open函数内部调用流程分析
c++·ffmpeg·音视频