设计模式复习-工厂方法模式
相对于简单工厂,工厂方法是把算法类的实例化延迟到了调用者那去做,调用者根据自己的需要,自己实例化相关的工厂并且生产相关算法。这么做是因为简单工厂是不满足OCP的,因为如果想添加新的算法,就得去改工厂函数里面的那个switch,这样容易在增加新的功能时引入新问题,而工厂方法不会导致这个问题,在算法扩充的时候满足OCP,不需要改之前原有的东西,直接往上加就行了。
//FactoryMode.h
#pragma once
//抽象算法接口
class CinterfaceAlgorithm {
public:
virtual bool GetValue(const int &nNumberA, const int &nNumberB, int &nNumberAns) = 0;
};
class CAddition : public CinterfaceAlgorithm {
public:
bool GetValue(const int &nNumberA, const int &nNumberB, int &nNumberAns) {
nNumberAns = nNumberA + nNumberB;
return true;
}
};
class CSubtraction : public CinterfaceAlgorithm {
public:
bool GetValue(const int &nNumberA, const int &nNumberB, int &nNumberAns) {
nNumberAns = nNumberA - nNumberB;
return true;
}
};
class CMultiplication : public CinterfaceAlgorithm {
public:
bool GetValue(const int &nNumberA, const int &nNumberB, int &nNumberAns) {
nNumberAns = nNumberA * nNumberB;
return true;
}
};
class CDivision : public CinterfaceAlgorithm {
public:
bool GetValue(const int &nNumberA, const int &nNumberB, int &nNumberAns) {
if (nNumberB == 0) {
return false;
}
nNumberAns = nNumberA / nNumberB;
return true;
}
};
//工厂接口
class CinterfaceFactory {
public:
virtual CinterfaceAlgorithm * GetFactoryBody() = 0;
};
class CAdditionFactory : public CinterfaceFactory {
CinterfaceAlgorithm * GetFactoryBody(){
return new CAddition();
}
};
class CSubtractionFactory : public CinterfaceFactory {
CinterfaceAlgorithm * GetFactoryBody() {
return new CSubtraction();
}
};
class CMultiplicationFactory : public CinterfaceFactory {
CinterfaceAlgorithm * GetFactoryBody() {
return new CMultiplication();
}
};
class CDivisionFactory : public CinterfaceFactory {
CinterfaceAlgorithm * GetFactoryBody() {
return new CDivision();
}
};
#include "stdafx.h"
#include "FactoryMode.h"
#include <iostream>
using namespace std;
int main() {
CinterfaceAlgorithm *pHashMemoryAlgorithm[10] = { 0 };
CinterfaceFactory * pHashMemoryFactory[10] = { 0 };
int nAlgorithmId = -1, nFactoryId = -1, nAns = 0;
pHashMemoryFactory[++nFactoryId] = new CAdditionFactory();
pHashMemoryAlgorithm[++nAlgorithmId] = pHashMemoryFactory[nFactoryId]->GetFactoryBody();
pHashMemoryFactory[++nFactoryId] = new CSubtractionFactory();
pHashMemoryAlgorithm[++nAlgorithmId] = pHashMemoryFactory[nFactoryId]->GetFactoryBody();
pHashMemoryFactory[++nFactoryId] = new CMultiplicationFactory();
pHashMemoryAlgorithm[++nAlgorithmId] = pHashMemoryFactory[nFactoryId]->GetFactoryBody();
pHashMemoryFactory[++nFactoryId] = new CDivisionFactory();
pHashMemoryAlgorithm[++nAlgorithmId] = pHashMemoryFactory[nFactoryId]->GetFactoryBody();
for (int nPoit = 0; nPoit <= nAlgorithmId; nPoit++) {
if (pHashMemoryAlgorithm[nPoit] != NULL && pHashMemoryAlgorithm[nPoit]->GetValue(1, 5, nAns)) {
cout << nAns << endl;
}
else {
cout << "Error" << endl;
}
}
for (int nPoit = 0; nPoit <= nAlgorithmId; nPoit++) {
delete pHashMemoryAlgorithm[nPoit];
delete pHashMemoryFactory[nPoit];
}
//getchar();
return 0;
}