利用多态来实现简单工厂模式(继承,纯虚函数)
下方例子展示不同面积的计算
#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
#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; }
#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; }
#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; } }
#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; }