【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;
	}
	
}
相关推荐
DK22151几秒前
计算机网络基础科普
c++·计算机网络
无畏烧风18 分钟前
[C++] 一个线程打印奇数一个线程打印偶数
c++
I AM_SUN20 分钟前
994. 腐烂的橘子
数据结构·c++·算法·leetcode·职场和发展
DARLING Zero two♡34 分钟前
C++色彩博弈的史诗:红黑树
c++·红黑树
龙湾开发1 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 09.天空和背景
c++·笔记·学习·3d·图形渲染
kyle~1 小时前
C++匿名函数
开发语言·c++·人工智能
李匠20241 小时前
C++GO语言微服务之Dockerfile && docker-compose
c++·docker·微服务·架构
code bean1 小时前
【Qt/C++】深入理解 Lambda 表达式与 `mutable` 关键字的使用
开发语言·c++·qt
Cuit小唐1 小时前
C++ 模板方法模式详解
java·c++·模板方法模式
序属秋秋秋1 小时前
《数据结构初阶》【堆 + 堆排序 + TOP-K】
c语言·数据结构·c++·笔记