【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;
	}
	
}
相关推荐
阿让啊1 小时前
C语言strtol 函数使用方法
c语言·数据结构·c++·单片机·嵌入式硬件
liulilittle2 小时前
OPENPPP2 —— IP标准校验和算法深度剖析:从原理到SSE2优化实现
网络·c++·网络协议·tcp/ip·算法·ip·通信
TechNomad2 小时前
设计模式:状态模式(State Pattern)
设计模式·状态模式
努力也学不会java2 小时前
【设计模式】 原型模式
java·设计模式·原型模式
TechNomad4 小时前
设计模式:模板方法模式(Template Method Pattern)
设计模式·模板方法模式
田里的水稻4 小时前
C++_队列编码实例,从末端添加对象,同时把头部的对象剔除掉,中的队列长度为设置长度NUM_OBJ
java·c++·算法
Jayden_Ruan5 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
liulun6 小时前
Skia如何渲染 Lottie 动画
c++·动画
leo03086 小时前
7种流行Prompt设计模式详解:适用场景与最佳实践
设计模式·prompt
点云SLAM6 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理