面向過程(POP): 關注「程序按什麼順序做哪些事」,核心問題:What are the things this program has to do? What procedures do we need?
面向對象(OOP): 關注「程序中有哪些事物(類)及其交互」,核心問題:What are the things in this program... who are the key players?
rotate(shapeNum) {
// make the shape rotate 360°
}
playSound(shapeNum) {
// use shapeNum to lookup which sound to play, and play it
}
以功能劃分模塊,數據(shapeNum)與操作分離,新增圖形需修改所有相關函數。
class Circle {
void rotate() { /* code to rotate a circle */ }
void playSound() { /* code to play sound for circle */ }
}
class Square {
void rotate() { /* code to rotate a square */ }
void playSound() { /* code to play sound for square */ }
}
將數據與行為封裝於類中,新增圖形只需新建類,符合開閉原則。
當需求變更(如新增三角形、修改旋轉邏輯),OOP 結構修改成本遠低於 POP。
「如果你在練習中卡住了,試著大聲說出來。聽覺能激活大腦不同區域。雖然找人討論最好,寵物也行——我家狗就是這樣學會多態的。」
編程學習重在親手嘗試、深度思考、學以致用,而非速讀書籍數量。