王國維在《人間詞話》說——古今之成大事業、大學問者,必經過三種之境界:"昨夜西風凋碧樹。獨上高樓,望盡天涯路。"此第一境也。"衣帶漸寬終不悔,為伊消得人憔悴。"此第二境也。"眾裡尋他千百度,驀然回首,那人卻在燈火闌珊處。"此第三境也。此等語皆非大詞人不能道。然遽以此意解釋諸詞,恐為晏歐諸公所不許也。"
高中時此三句詩已熟記於心,工作兩年來,自詡努力讀書學習,其實不過九牛之一毛,還沒入得門徑。
從前天開始,捧起《大話設計模式》,看了起來。
小菜我工作兩年,大學期間有一點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請按任意鍵繼續. . .