Java教程

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

本文主要是介绍工厂模式(简单工厂模式,抽象工厂模式),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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.抽象工厂模式 

这篇关于工厂模式(简单工厂模式,抽象工厂模式)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!