【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;
	}
	
}
相关推荐
m0_535064606 小时前
C++模版编程:类模版与继承
java·jvm·c++
Tanecious.7 小时前
C++--红黑树封装实现set和map
网络·c++
DKPT7 小时前
Java设计模式之行为型模式(观察者模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
络78 小时前
Java4种设计模式详解(单例模式、工厂模式、适配器模式、代理模式)
单例模式·设计模式·代理模式·适配器模式·工厂模式
贱贱的剑9 小时前
5.适配器模式
设计模式·适配器模式
JouJz9 小时前
设计模式之工厂模式:对象创建的智慧之道
java·jvm·设计模式
愚润求学10 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
源代码•宸11 小时前
C++高频知识点(十三)
开发语言·c++·经验分享·面经
极光雨雨11 小时前
【设计模式】备忘录模式(标记(Token)模式)
设计模式·备忘录模式
lhxcc_fly11 小时前
mmap映射文件
c++·地址映射文件·!fd