前言
學校作業做一做突然覺得每次都只是把功能硬幹出來好像沒什麼用(而且好醜 Orz),應該要加入一些不曾使用過的技巧或思維,於是試著從「用 C 來做物件導向程式設計」開始。
實際上看過的文章不多,目前有應用上的也只有利用函式指標來做到類似 C++ 成員函式的功能,寫起來有比以前乾淨些,不過對於架構的設計方面仍舊覺得卡卡的,於是開始研究下設計樣式。
在這邊紀錄一些看過的關於設計樣式的文章。
"Patterns" that are used recurringly in one language may be invisible or trivial in a different language.
關於設計樣式的定義,作者提到了兩種,一種是四人幫 GoF 所提出的,另一種是維基百科上的:
- GoF
- 設計樣式系統性地描述在物件導向的系統設計過程中反覆出現的設計。「描述」包含了意涵、解決方案、使用的時機、會造成的結果以及實作上的提示與範例。解決方案通常是一系列的物件或類別的設計,而不是某個程式或是某段程式碼,因此這個設計必須針對特定的應用情況來客製化與實做的。
- A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. The solution is a general arrangement of objects and classes that solve the problem. The solution is customized and implemented to solve the problem in a particular context.
- Wikipedia
- 在軟體工程中,設計樣式通常是一個對於軟體設計上常見問題的解決方案。設計樣式並非是一個可以直接轉換成程式碼的完整設計,它是一個對於某問題的解決方案的描述 / 模板,且可以被使用在許多不同的情境下。
- In software engineering, a design pattern is a general solution to a common problem in software design. A design pattern isn't a finished design that can be transformed directly into code; it is a description or template for how to solve a problem that can be used in many different situations.
樣式的法則(Codification of patterns)
Peter Norvig 在演講 "Design Patterns in Dynamic Languages" 中將樣式的實作分成三個等級:
- Invisible
- 被語言本身的特性給隱藏起來,像是使用 C++ 的 private, public。
- 作者提到早期開發 C++ 的動機之一就是為了將一些樣式加入語言本身,來達到 invisible。要注意的是,在背後運作時,運作的原理跟自行實做是一樣的,甚至早期的 C++ 編譯器會先將 C++ 轉換成相等的 C 程式碼並編譯(講古?!)。
- Informal
- 由程式設計師利用現有語法實做出來的,像是自行設計並使用 C 來做到物件導向的類別。特點是換了不同對象就必須從頭寫起。
- Formal
- 跟 informal 類似,不過多半以 macro 實做,因此可以快速地為不同對象做出相同的樣式。特點是雖然不需要像 informal 從頭寫起,但是需要特別去實體化 / 呼叫來使用。
程式語言的演進
多數樣式並非在處理重複發生的設計問題,實際上是在指出某語言的缺陷,在其他的語言中,同樣的問題可能不會出現或是可以很輕鬆地解決。舉例來說,在 assembly 語言中,"subroutine call" 需要實做特定樣式,但在 C 語言中只需要簡單地寫 result = function(args...)。因此,"Design Patterns" 不應該只是用來訓練程式設計師,讓他們能夠辨別情境並使用適當的樣式,而是用來發展語言的,隨著程式語言演進,讓某些樣式可以存在在語言本身,程式設計師才能夠專注在使用某些樣式,而非實做它。
總結
Patterns are signs of weakness in programming languages.
When we identify and document one, that should not be the end of the story. Rather, we should have the long-term goal of trying to understand how to improve the language so that the pattern becomes invisible or unnecessary.
前言
Design patterns of 1972
關於設計樣式的定義,作者提到了兩種,一種是四人幫 GoF 所提出的,另一種是維基百科上的:
樣式的法則(Codification of patterns)
Peter Norvig 在演講 "Design Patterns in Dynamic Languages" 中將樣式的實作分成三個等級:
程式語言的演進
多數樣式並非在處理重複發生的設計問題,實際上是在指出某語言的缺陷,在其他的語言中,同樣的問題可能不會出現或是可以很輕鬆地解決。舉例來說,在 assembly 語言中,"subroutine call" 需要實做特定樣式,但在 C 語言中只需要簡單地寫
result = function(args...)。因此,"Design Patterns" 不應該只是用來訓練程式設計師,讓他們能夠辨別情境並使用適當的樣式,而是用來發展語言的,隨著程式語言演進,讓某些樣式可以存在在語言本身,程式設計師才能夠專注在使用某些樣式,而非實做它。總結