前言
最近在看程杰的《大话设计模式》,希望掌握现有的优秀软件设计思想,提升内功修为。本书的示例代码为C#,之前并没有学过C#,借此次机会,正好学习一下。另外,我仿照示例代码,将其修改为C++代码,一是为了加深理解,只有动手敲代码体会才会更深;二是为了比较C++与C#某些细节处的不同。
简单工厂模式C++代码
Operation.h
#pragma once
class Operation {
protected:
int numberA;
int numberB;
public:
Operation() {};
virtual double getResult() const= 0;
void setNumberA(int _numberA) {numberA = _numberA;}
void setNumberB(int _numberB){numberB = _numberB;}
int getNumberA() const{return numberA;}
int getNumberB() const{return numberB;}
};
class OperationAdd :public Operation
{
public:
double getResult() const;
};
class OperationSub :public Operation
{
public:
double getResult() const;
};
class OperationMul :public Operation
{
public:
double getResult() const;
};
class OperationDiv :public Operation
{
public:
double getResult() const;
};
class OperationFactory {
public:
static Operation* createOperate(char oper);
};
Operation.cpp
#include"Operation.h"
double OperationAdd::getResult() const
{
return double(getNumberA() + getNumberB());
}
double OperationSub::getResult() const
{
return double(numberA - numberB);
}
double OperationMul::getResult() const
{
return double(numberA*numberB);
}
double OperationDiv::getResult() const
{
if (numberB == 0)
throw "除数不能为0";
return double(numberA) / numberB;
}
Operation* OperationFactory::createOperate(char oper)
{
Operation *operation=nullptr;
switch (oper)
{
case '+':operation = new OperationAdd; break;
case '-':operation = new OperationSub; break;
case '*':operation = new OperationMul; break;
case '/':operation = new OperationDiv; break;
}
return operation;
}
main.cpp
#include<iostream>
#include"Operation.h"
using namespace std;
int main()
{
try {
int numberA;
int numberB;
char oper;
double result;
cout << "请输入numberA:";
cin >> numberA;
cout << "请输入运算符(+、-、*、/):";
cin >> oper;
cout << "请输入numberB:";
cin >> numberB;
Operation *operation = nullptr;
operation = OperationFactory::createOperate(oper);
operation->setNumberA(numberA);
operation->setNumberB(numberB);
result = operation->getResult();
cout << "结果为:" << result << endl;
delete operation;
operation = nullptr;
}
catch (const char *msg) {
cout << msg << endl;
}
return 0;
}
笔记
(1)为什么简单工厂模式又称为静态工厂方法?
创建具体产品时所使用的的方法为静态方法(函数),不需要先创建工厂类对象,再调用方法。即createOperate()是静态函数,可以这样直接调用:OperationFactory::createOperate(oper)
,而不需要先创建对象,再进行调用:OperationFactory factory;factory.createOperate(oper)
(2)工厂类、抽象产品类、具体产品类
- 具体产品类:
OperationAdd
、OperationSub
、OperationMul
、OperationDiv
等具体的运算类。 - 抽象产品类:
Operation
,具体产品类的父类,定义虚函数接口等。 - 工厂类:
OperationFactory
,简单工厂模式的核心,负责创建具体产品类。
参考
https://www.jb51.net/article/55858.htm
https://www.cnblogs.com/jostree/p/4251756.html