1.简单工厂模式

UML类图

代码

main.cpp

cpp 复制代码
#include <iostream>
#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

cpp 复制代码
#include"Operation.h"
#include<string>
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

cpp 复制代码
 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;
	 }
 };
相关推荐
醇醛酸醚酮酯18 天前
简单工厂模式,工厂模式和注册工厂模式
简单工厂模式
山海上的风21 天前
23种设计模式--简单工厂模式理解版
java·开发语言·简单工厂模式
OpenC++22 天前
【C++】简单工厂模式/工厂方法模式/抽象工厂模式对比
c++·设计模式·简单工厂模式·工厂方法模式·抽象工厂模式
h201701068724 天前
简单工厂、工厂、抽象工厂模式
简单工厂模式·工厂方法模式·抽象工厂模式
积跬步至千里PRO1 个月前
在 Java 中实现一个标准 Service 接口,并通过配置动态选择具体实现类供 Controller 调用
java·简单工厂模式·解耦
逆风飞翔i1 个月前
简单工厂模式
c++·简单工厂模式
蔡蓝1 个月前
设计模式-简单工厂模式
设计模式·简单工厂模式
{⌐■_■}1 个月前
【设计模式】简单工厂模式,工厂模式,抽象工厂模式,单例,代理,go案例区分总结
开发语言·redis·后端·设计模式·golang·简单工厂模式·抽象工厂模式
on the way 1231 个月前
Simple Factory(简单工厂)
java·简单工厂模式
~小先生~1 个月前
设计模式——简单工厂模式
设计模式·c#·简单工厂模式