C++设计模式 ==> 工厂模式
简介
在之前,笔者曾简单介绍过简单工厂模式,我们说过简单工厂模式可以使用工厂类根据需求动态生成子类对象,从而方便了未来对算法进行维护和扩展。而工厂模式相较之于简单工厂模式更为复杂,工厂模式对工厂类进行了详细的子类化,为每一个算法都建立了独立的工厂,这样的优点在于可以在算法扩展的时候避免修改总工厂类,而只要生成相应的子类就可以了,尽可能避免了违背“开闭原则”的情况,但缺点在于这样switch一类的条件判断就必须从原来的工厂类搬到了客户端。下面我们通过一个和当时在简单工厂模式章节一样的计算器算法的例子实现一下工厂模式。
图示
代码实现
////////////////////////////
//
// @Author : PeterZheng
// @FileName : FactoryModeDefine.h
// @Date : 2018-08-13 19:17
//
////////////////////////////
#pragma once
#ifndef FMDINCLUDE
#define FMDINCLUDE
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <windows.h>
#endif
//运算符操作类
class Operation
{
public:
double _numberA = 0;
double _numberB = 0;
double result = 0;
virtual double GetResult() { return 0.0; };
};
//总工厂类
class IFactory
{
public:
virtual Operation* CreateFactory() = 0;
};
//加法操作类
class AddOperation : public Operation
{
virtual double GetResult()
{
return _numberA + _numberB;
}
};
//减法操作类
class SubOperation : public Operation
{
virtual double GetResult()
{
return _numberA - _numberB;
}
};
//乘法操作类
class MulOperation : public Operation
{
virtual double GetResult()
{
return _numberA * _numberB;
}
};
//除法操作类
class DivOperation : public Operation
{
virtual double GetResult()
{
if (_numberB != 0)
return _numberA / _numberB;
else
ExitProcess(0);
}
};
//加法工厂类
class AddOpFactory : public IFactory
{
virtual Operation* CreateFactory()
{
return new AddOperation();
}
};
//减法工厂类
class SubOpFactory : public IFactory
{
virtual Operation* CreateFactory()
{
return new SubOperation();
}
};
//乘法工厂类
class MulOpFactory : public IFactory
{
virtual Operation* CreateFactory()
{
return new MulOperation();
}
};
//除法工厂类
class DivOpFactory : public IFactory
{
virtual Operation* CreateFactory()
{
return new DivOperation();
}
};
////////////////////////////
//
// @Author : PeterZheng
// @FileName : FMDemo.cpp
// @Date : 2018-08-13 19:50
//
////////////////////////////
#include "FactoryModeDefine.h"
int main(void)
{
double _numberA = 0;
double _numberB = 0;
char symbol = '\0';
Operation *op = NULL;
IFactory *ft = NULL;
scanf("%lf %c %lf", &_numberA, &symbol, &_numberB);
switch (symbol)
{
case '+':
ft = new AddOpFactory();
break;
case '-':
ft = new SubOpFactory();
break;
case '*':
ft = new MulOpFactory();
break;
case '/':
ft = new DivOpFactory();
break;
default:
ExitProcess(0);
}
op = ft->CreateFactory();
op->_numberA = _numberA;
op->_numberB = _numberB;
op->result = op->GetResult();
std::cout << op->result << std::endl;
system("pause");
return 0;
}
本文为博主总结文章,欢迎转载,请注明出处。