【CPP】设计模式一工厂模式

本文通过一个汽车购买的例子展示了工厂模式的应用,用户只需提出需求,工厂负责创建具体的汽车对象(如圆形、矩形或正方形)。代码实例中定义了一个`Shape`接口及其实现类`Square`、`Rectangle`和`Circle`,然后创建了`ShapeFactory`用于根据输入生成相应的形状对象,简化了对象创建过程。
摘要由CSDN通过智能技术生成

工厂模式---你提需求,我实现


在这里插入图片描述

应用实例

用户需要一辆汽车,可以直接从工厂里面提货,而不用去管这辆汽车是怎么做出来的,以及这个汽车里面的具体实现细节

代码实例

创建一个接口

class Shape{
public:
	virtual void draw() = 0;
}

创建实现接口的实体类

class Squre: public Shape{
public:
	void draw(){
		cout<<"Image that it drawn a Squre."<<endl;
	}
}
class Rectangle: public Shape{
public:
	void draw(){
		cout<<"Image that it drawn a Rectangle."<<endl;
	}
}
class Circle: public Shape{
public:
	void draw(){
		cout<<"Image that it drawn a Circle."<<endl;
	}
}

创建一个工厂,生成给定信息的实体类的对象

class ShapeFactory{
	Shape getShape(string shapetype){
		if(ShapeType == "Circle") reutrn new Circle();
		else if(ShapeType == "Rectangle") reutrn new Rectangle();
		else if(ShapeType == "Squre") reutrn new Squre();
		else return nullptr;
	}
}

使用工厂传递信息获取实体类的对象

void FactoryPattrenDemo(){
	ShapeFactory ShapeF = new ShapeFactory();
	
	Shape s1, s2, s3;
	s1 = ShapeF.getShape("Circle");
	s1.draw();
	s2 = ShapeF.getShape("Rectangle");
	s2.draw();
	s3 = ShapeF.getShape("Squre");
	s3.draw();
	return;
}
int main(){
	FactoryPattrenDemo();
	return 0;
}

输出:

Image that it drawn a Circle.
Image that it drawn a Rectangle.
Image that it drawn a Squre.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值