【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;
	}
	
}
相关推荐
oioihoii8 分钟前
现代C++:一场静默的革命,告别“C with Classes”
c语言·jvm·c++
明洞日记33 分钟前
【设计模式手册007】原型模式 - 通过复制创建对象的艺术
java·设计模式·原型模式
普通网友41 分钟前
C++中的组合模式
开发语言·c++·算法
江公望1 小时前
Qt QByteArray类型,10分钟讲清楚
开发语言·c++·qt
2501_941111461 小时前
C++中的组合模式变体
开发语言·c++·算法
普通网友1 小时前
单元测试在C++项目中的实践
开发语言·c++·算法
沐怡旸2 小时前
【穿越Effective C++】条款22:将成员变量声明为private——封装的边界与设计的自由
c++
u***j3243 小时前
算法设计模式总结
算法·设计模式
烤麻辣烫3 小时前
23种设计模式(新手)-7迪米特原则 合成复用原则
java·开发语言·学习·设计模式·intellij-idea
G***66914 小时前
算法设计模式:贪心与动态规划
算法·设计模式·动态规划