原文中的故事很有趣如下:
“One comment I saw in a news group just after patterns started to become more popular was someone claiming that in a particular program they tried to use all 23 GoF patterns. They said they had failed, because they were only able to use 20. They hoped the client would call them again to come back again so maybe they could squeeze in the other 3.
Trying to use all the patterns is a bad thing, because you will end up with synthetic designs—speculative designs that have flexibility that no one needs. These days software is too complex. We can’t afford to speculate what else it should do. We need to really focus on what it needs.” – Erich Gamma
上述大意是說有個團隊想要在程式中套用GoF四人幫所有的23種Design Patterns,但是最後失敗了,因為只套用了其中20種,他們希望客戶最後還會請他們將最後3種Design Patterns也套用上去.
使用所有的Pattern不是個好主意,最終會使軟體架構變得太複雜,而且設計了永遠用不到的彈性,其實只要專注在當下產品所需要才是正道.
由於原文是使用Java當作範例,這邊我除了將它改寫為C#外,也加了一些改變:
1. 首先最基本的Hello World:
2. 定義 觀察者模式(Observer Pattern) 的主題與訂閱者
3. 實作主題與訂閱者的類別
4. 命令模式(Command Pattern) 的介面與實作
5. 抽象工廠模式(Abstract Factory) 的介面與實作
6. 單例模式 (Singleton),這邊使用Double checked locking,濫用得徹底一點 XD
7. 讓這複雜的Hello World動起來吧:
8.執行結果,這麼精美的一行...
原文有做了一些結論:
- 對於單純了Hello World程式來說太複雜了
- 我們加了一些根本就用不到的程式彈性
- 整個系統的分析與設計浪費太多時間
- 造成了類別爆炸(class explosion)
- 違反KISS原則(Keep it simple, stupid!)
- 這不是原始程式的目的,原始程式只是在命令列印出一行Hello World,現在這個程式碼離這個目.
Reference:
The Abuse of Design Patterns in writing a Hello World Program