簡介
在之前蛋褥,筆者曾簡單介紹過簡單工廠模式吮成,我們說過簡單工廠模式可以使用工廠類根據(jù)需求動(dòng)態(tài)生成子類對(duì)象频丘,從而方便了未來對(duì)算法進(jìn)行維護(hù)和擴(kuò)展蓝仲。而工廠模式相較之于簡單工廠模式更為復(fù)雜俱病,工廠模式對(duì)工廠類進(jìn)行了詳細(xì)的子類化,為每一個(gè)算法都建立了獨(dú)立的工廠杂曲,這樣的優(yōu)點(diǎn)在于可以在算法擴(kuò)展的時(shí)候避免修改總工廠類庶艾,而只要生成相應(yīng)的子類就可以了,盡可能避免了違背“開閉原則”的情況擎勘,但缺點(diǎn)在于這樣switch一類的條件判斷就必須從原來的工廠類搬到了客戶端咱揍。下面我們通過一個(gè)和當(dāng)時(shí)在簡單工廠模式章節(jié)一樣的計(jì)算器算法的例子實(shí)現(xiàn)一下工廠模式。
圖示
代碼實(shí)現(xiàn)
////////////////////////////
//
// @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
//運(yùn)算符操作類
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;
}