最近在阅读一本书 大话设计模式,读到这本书是一种打开一扇门的感觉。相信很多人学习过OO,但是大多数人应该和我一样,停留在了概念和语法层面。一段代码读懂已经不易,更别提设计代码。另外一方面,本来的工程项目做的不多,根本没有太多的机会学习构建类的系统方法。
花了3天时间将大话设计模式过了一遍,但是其中的精妙不是短短时间就能吸收的。学习编程的方法应该是多跑程序,多读程序。此外,大话设计模式中的代码都是通过c#编写的,对于绝大多数人来说,相对遥远。很多机制也是不一样的。最好的总结就是写出代码,因此,我决定自己独立的实现一遍。
#include<iostream>
#include<vector>
#include<cstdlib>
#include<string>
using namespace std;
class operation
{
public:
virtual double getresult()=0;
double numberA;
double numberB;
};
class operationadd:public operation
{
public:
double getresult()
{
return numberA+numberB;
}
};
class operationsub:public operation
{
public:
double getresult()
{
return numberA-numberB;
}
};
class operationmul:public operation
{
public:
double getresult()
{
return numberA*numberB;
}
};
class operationdiv:public operation
{
public:
double getresult()
{
if(numberB==0)exit(1);
return numberA/numberB;
}
};
class operationfactory
{
public:
static operation *createoperation(string opera)
{
operation *oper=NULL;
if(opera==string("+"))
oper= (operation*)new operationadd();
if(opera==string("-"))
oper= (operation*)new operationsub();
if(opera==string("*"))
oper= (operation*)new operationmul();
if(opera==string("/"))
oper= (operation*)new operationdiv();
return oper;
}
};
int main()
{
operation* oper;
oper=operationfactory::createoperation("-");
oper->numberA=1;
oper->numberB=2;
cout<<oper->getresult()<<endl;
system("pause");
return 0;
}