【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;
	}
	
}
相关推荐
biter down几秒前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
ShineWinsu1 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
charlie1145141912 小时前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32
DpHard2 小时前
现代 C++ 中 push 接口为何提供 const T& 与 T&& 两个重载
c++
U-52184F693 小时前
深度解析:从 Qt 的 Q_D 宏说起,C++ 工业级 SDK 是如何保证 ABI 稳定性的
数据库·c++·qt
泯仲4 小时前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
hz_zhangrl4 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
kyle~5 小时前
C++----函数指针与函数指针类型 返回值类型 (*类型名)(参数列表)
开发语言·c++
努力中的编程者5 小时前
二叉树(C语言底层实现)
c语言·开发语言·数据结构·c++·算法
WarrenMondeville6 小时前
1.Unity面向对象-单一职责原则
unity·设计模式·c#