1.简单工厂模式

UML类图

1.简单工厂模式_第1张图片

代码

main.cpp

#include 
#include "OperationFactory.h"
using namespace std;

int main(void) {

	float num1;
	float num2;
	char operate;
	cin >> num1 >> num2 >> operate;
	Operation* oper = OperationFactory::createOperate(operate);
	oper->setnumA(num1);
	oper->setnumB(num2);
	double result = oper->getResult();
	cout << result << endl;

	return 0;
}

OperationFactory.h

#include"Operation.h"
#include
using namespace std;
class OperationFactory {
public:
	static Operation* createOperate(char operate) {
		Operation *oper = NULL;
		switch (operate) {
		case '+':
			oper = new OperationAdd();
			break;
		case '-':
			oper = new OperationSub();
			break;
		case '*':
			oper = new OperationMul();
			break;
		case '/':
			oper = new OperationDiv();
			break;
		}
		return oper;
	}
};

Operation.h

 class Operation {//运算类基类

 protected:
	 float numA = 0;
	 float numB = 0;

 public:
	 void setnumA(float paramA) {
		 numA = paramA;
	 }
	 void setnumB(float paramB) {
		 numB = paramB;
	 }
	 virtual float getResult() {
		 float result = 0;
		 return result;
	 }

};


 class OperationAdd :public Operation {//加法类派生类

 public:
	 float getResult() {
		 float result = 0;
		 result = numA + numB;
		 return result;
	 }

 };

 class OperationSub :public Operation {//派生减法类

 public:
	 float getResult() {
		 float result = 0;
		 result = numA - numB;
		 return result;
	 }
 };

 class OperationMul :public Operation {//派生乘法类
 public:
	 float getResult() {
		 float result = 0;
		 result = numA * numB;
		 return result;
	 }
 };

 class OperationDiv :public Operation {//派生除法类
 public:
	 float getResult() {
		 float result = 0;
		 result = numA / numB;
		 return result;
	 }
 };

你可能感兴趣的:(设计模式,简单工厂模式)