關(guān)于POP和OOP的解釋我想網(wǎng)上的資料已經(jīng)數(shù)不勝數(shù)了,但是基本無非都是在擺理論。剛好本人既寫過面向過程(POP)的C程序也寫過面向?qū)ο螅∣OP)的C#程序,甚至是萬物皆對(duì)象的Python程序。下面本人就從自身的實(shí)際感受來給大家淺顯易懂的解析一下什么是面向?qū)ο缶幊?/p>
面向?qū)ο蟾菀鬃屓死斫?/strong>
其實(shí)object也可以翻譯為物件,我想這個(gè)詞對(duì)于初學(xué)者肯定比對(duì)象更友好。以前的pop思想其實(shí)就是過程導(dǎo)向,就是我想實(shí)現(xiàn)一個(gè)什么樣的計(jì)算結(jié)果,然后用變量和函數(shù)將這個(gè)結(jié)果實(shí)現(xiàn),但是這樣很抽象化,初學(xué)者較難理解。但是面向?qū)ο蟮脑拰⒊橄蟮母拍疃冀o你具像化了,是以物件為主導(dǎo)。接下來我用一段對(duì)比代碼展示可能更容易理解。
比如,我要計(jì)算兩個(gè)人繞著操場(chǎng)跑一圈的時(shí)間。
左邊是面向過程的,右邊是面向?qū)ο蟮?。其?shí)面向?qū)ο螅憧梢詫⑺?運(yùn)算符理解為我們漢語的‘的’,這樣更容易讓程序員理解
封裝
然后就講到面向?qū)ο蟮姆庋b,如上右圖。面向?qū)ο罂梢詫⑺俣?、距離等全部封裝在一個(gè)抽象的類中,然后再通過new操作來具像化對(duì)象,而面向過程只能通過函數(shù)和變量來存儲(chǔ)數(shù)據(jù)和運(yùn)算。這樣當(dāng)一個(gè)工程夠大的時(shí)候,面向?qū)ο蟮某绦蚋菀拙S護(hù),且重用性也更好
繼承和多態(tài)
繼承和多態(tài)的話是面向?qū)ο笞钪饕奶卣?。其?shí)也很好理解。還是拿上面那個(gè)例子,現(xiàn)在有一個(gè)小孩,他除了run這個(gè)動(dòng)作外還需要加一個(gè)喝奶(drinkMilk)動(dòng)作,那么小孩子也屬于人這一類,我是不是可以不用再去重復(fù)的寫關(guān)于Run這個(gè)動(dòng)作的相關(guān)代碼呢?由此,繼承的概念就出來了。
namespace test0923 { class People { public double speed { get; set; } public double distance { get; set; } public double time { get; set; } public People() { } public People(double distance ,double speed) { this.distance = distance; this.speed = speed; } public double Run() { return this.distance / this.speed; } } class Children:People { public void drinkMilk() { Console.WriteLine("milk is very delicious"); } } class Progaram { static void Main(string[] args) { People xiaoMing = new People(100,10); xiaoMing.time = xiaoMing.Run(); People xiaoHua = new People(120, 12); xiaoHua.time = xiaoHua.Run(); Children baby = new Children(); baby.distance = 100; baby.speed = 2; baby.Run(); baby.drinkMilk(); } } }
那么另外一個(gè)問題又來了,小孩Run可能速度計(jì)算不能跟大人一樣,可能需要自己的計(jì)算方法,那么怎么辦呢?這時(shí)候,多態(tài)的概念又出來了。我們只需要給父類的即People的Run方法加上virtual,再在子類中加override就可以了
namespace test0923 { class People { public double speed { get; set; } public double distance { get; set; } public double time { get; set; } public People() { } public People(double distance ,double speed) { this.distance = distance; this.speed = speed; } public virtual double Run() { return this.distance / this.speed; } } class Children:People { public override double Run() { return this.distance/this.speed + 10; } public void drinkMilk() { Console.WriteLine("milk is very delicious"); } } class Progaram { static void Main(string[] args) { People xiaoMing = new People(100,10); xiaoMing.time = xiaoMing.Run(); People xiaoHua = new People(120, 12); xiaoHua.time = xiaoHua.Run(); Children baby = new Children(); baby.distance = 100; baby.speed = 2; baby.Run(); Console.WriteLine(baby.Run()); baby.drinkMilk(); Console.Read(); } } }
怎么樣,現(xiàn)在對(duì)面向?qū)ο笥幸粋€(gè)大概的了解了吧。相比面向過程,面向?qū)ο蟮乃枷朐诰帉懘笮晚?xiàng)目時(shí)代碼更容易維護(hù)、更易懂、代碼重用率更高。但相對(duì)的犧牲的就是運(yùn)行的效率了。