设计模式之---简单工厂模式
简单工厂模式:到底要实例化哪个对象,将来会不会增加实例化对象,这时可以考虑用一个单独的类来创造实例的过程,这就是工厂。
以一个2元操作运算来说明:
operator类:
// SimpleFactory.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "Factory.h"#include "Factory.cpp"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){CFactory<double> *pFac=new CFactory<double>;COperator<double>* pOpe=NULL;double result;pOpe=pFac->CreateOperator('+');if(pOpe!=NULL){result = pOpe->GetResult(2,3);cout<<"2 + 3 = "<<result<<endl;delete pOpe;}pOpe=pFac->CreateOperator('-');if(pOpe!=NULL){result = pOpe->GetResult(2,3);cout<<"2 - 3 = "<<result<<endl;delete pOpe;}pOpe=pFac->CreateOperator('*');if(pOpe!=NULL){result = pOpe->GetResult(2,3);cout<<"2 * 3 = "<<result<<endl;delete pOpe;}pOpe=pFac->CreateOperator('/');if(pOpe!=NULL){result = pOpe->GetResult(2,3);cout<<"2 / 3 = "<<result<<endl;delete pOpe;}return 0;}