其他分享
首页 > 其他分享> > 工厂模式(简单工厂模式,抽象工厂模式)

工厂模式(简单工厂模式,抽象工厂模式)

作者:互联网

1.简单工厂模式

利用多态来实现简单工厂模式(继承,纯虚函数)

下方例子展示不同面积的计算

1.1.父类(仅实现头文件即可,用纯虚函数,析构函数设置为虚函数)

#ifndef AREA_H
#define AREA_H
#include <iostream>
using namespace std;

class Area
{
public:
	virtual void showArea() = 0;
	virtual float calcuArea() = 0;
	virtual ~Area() {}

};

#endif // !AREA_H

1.2实际产品(此处以圆和矩形作为例子)

1.2.1圆

#ifndef CIRCLE_H
#define CIRCLE_H
#include "area.h"
class Circle :public Area
{
public:
	Circle(float radius);
	virtual void showArea();
	virtual float calcuArea();
	virtual ~Circle() {}
private:
	float _Cradius;
};

#endif // !CIRCLE_H
#include "circle.h"

Circle::Circle(float radius)
	:_Cradius(radius)
{

}
void Circle::showArea()
{
	cout << "Circle: ";
}

float Circle::calcuArea()
{
	return 3.14*_Cradius*_Cradius;
}

1.2.2矩形

#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "area.h"

class Rectangle :public Area
{
public:
	Rectangle(float length, float width);
	virtual void showArea();
	virtual float calcuArea();
	virtual ~Rectangle() {}
private:
	float _Rlegth;
	float _Rwidth;
};


#endif
#include "rectangle.h"

Rectangle::Rectangle(float length, float width)
	:_Rlegth(length), _Rwidth(width)
{

}

void Rectangle::showArea()
{
	cout << "Rectangle: ";
}

float Rectangle::calcuArea()
{
	return _Rlegth * _Rwidth;
}

1.3工厂

#ifndef AREAFACTORY_H
#define AREAFACTORY_H
#include "circle.h"
#include "rectangle.h"

enum AREA_TYPE
{
	CIRCLE = 0,
	RECTANGLE
};

class Areafactory
{
public:
	Area* calcuDiffArea(AREA_TYPE type);
};

#endif // !AREAFACTORY_H
#include "areaFactory.h"
Area* Areafactory::calcuDiffArea(AREA_TYPE type)
{
	switch (type)
	{
	case CIRCLE:
		return new Circle(10);
		break;
	case RECTANGLE:
		return new Rectangle(4, 5);
		break;
	default:
		break;
	}
}

1.4主函数

#include "areaFactory.h"

int main()
{
	Areafactory *pAreaFactory = new Areafactory();
	Area *pCircleArea = pAreaFactory->calcuDiffArea(CIRCLE);
	if (nullptr == pCircleArea) {
		return 0;
	}
	pCircleArea->showArea();
	cout << pCircleArea->calcuArea();
	delete pCircleArea;
	pCircleArea = nullptr;
	cout << endl;

	Area *pRectangleArea = pAreaFactory->calcuDiffArea(RECTANGLE);
	pRectangleArea->showArea();
	cout<<pRectangleArea->calcuArea();
	delete	pRectangleArea;
	pRectangleArea = nullptr;

	delete pAreaFactory;
	pAreaFactory = nullptr;
	return 0;
}

2.抽象工厂模式 

标签:Area,float,virtual,工厂,抽象,模式,Circle,include,Rectangle
来源: https://blog.csdn.net/hfwyydy/article/details/122531174