王国维在《人间词话》说——古今之成大事业、大学问者,必经过三种之境界:"昨夜西风凋碧树。独上高楼,望尽天涯路。"此第一境也。"衣带渐宽终不悔,为伊消得人憔悴。"此第二境也。"众里寻他千百度,蓦然回首,那人却在灯火阑珊处。"此第三境也。此等语皆非大词人不能道。然遽以此意解释诸词,恐为晏欧诸公所不许也。"
高中时此三句诗已熟记于心,工作两年来,自诩努力读书学习,其实不过九牛之一毛,还没入得门径。
从前天开始,捧起《大话设计模式》,看了起来。
小菜我工作两年,大学期间有一点C基础。大学期间最后一年决定学习JAVA,于是苦苦自学一年。毕业后工作两年C++。去年时也曾读过《大话设计模式》第一章,但是看不出啥感觉来,只是用VS2010创建一个C#的项目,把代码照敲进去。可能是水平差,抑或不得方法。这一年又写了好多程序,做过几个小项目,再读此书,感觉轻松一些,起码可以读懂。
书中是用C#代码来实现,我并没有学习过C#,但是学习过C++java,读起代码来基本上没有难度。为了不只停留于表面看得懂,我尝试用C++依照例子重写了上边的例子程序,也挺简单,不同的可能是要多用到指针,注意内存的分配与释放,注意C#与C++的区别,在必要的地方使用virtual,比如C++不能使用“base.”。对于C++比较熟悉或者对C++函数表有所了解的同学,即使完全 没有学习过c#,也不会有太大的难度。
// CalculatorTest01.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; //运算抽象类 class Operator { public : int num1; int num2; public : virtual int GetResult()=0; }; //加法运算类 class OperatorAdd : public Operator { public : int GetResult() { return this->num1 + this->num2; } }; //减法运算类 class OperatorSub : public Operator { public : int GetResult() { return this->num1 - this->num2; } }; //运算工厂类 class OperationFactory { public : static Operator* GetOperator(char ch) { Operator* oper; switch(ch) { case '+': oper = new OperatorAdd; break; case '-': oper = new OperatorSub; break; } return oper; } }; int _tmain(int argc, _TCHAR* argv[]) { int num1, num2; char operate; cout<<"请输入第一个数:"<<endl; cin>>num1; cout<<"请输入第二个数:"<<endl; cin>>num2; cout<<"请输入运算符:"<<endl; cin>>operate; Operator* oper = OperationFactory::GetOperator(operate); oper->num1 = num1; oper->num2 = num2; int result = oper->GetResult(); cout<<num1<<" "<<operate<<" "<<num2<<" = "<<result<<endl; delete oper; system("pause\n"); return 0; }
面向对象的好处:通过封装、继承、多态把程序的耦合度降低。
程序运行测试:
请输入第一个数: 3 请输入第二个数: 8 请输入运算符: - 3 - 8 = -5 请按任意键继续. . .