This repository was archived by the owner on Apr 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
767b335
commit 437ec28
Showing
2 changed files
with
29 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
--- | ||
layout: post | ||
title: GoF 閱讀筆記(Creational Patterns) | ||
--- | ||
|
||
近日在讀 _Design Patterns: Elements of Reusable Object-Oriented Software_ (又稱 _GoF_ ) 一書。本以為需要硬啃,讀起來卻還算流暢。讀到已經在工作中讀過或寫過的模式時,大體沒甚麼壓力。而在學習新模式時,會想到手頭的項目哪些地方會適合使用這個模式,幫助了理解。如果是在上學時讀到,沒甚麼項目經歷,腦袋空空的,那就會覺得讀著艱澀吧。 | ||
|
||
_GoF_ 將設計模式分為了三類。第一類與對象的創建有關,稱為 Creational Patterns。 | ||
|
||
### Abstract Factory 抽象工廠 | ||
|
||
抽象工廠適用於創建一族相關聯的對象。工作上並沒有使用過這個模式,之前就一直搞不清楚它和工廠方法的區別。書中以建創不同的 UI 平臺上的窗口、按鍵等元件為例,讀後豁開朗。兩者的關鍵區別在於抽象工廠著眼於**一族**對象,而工廠方法僅僅關注**一個**對象。如果改變平臺,窗口、按鍵等全部元件的實現都需要切換到相應平臺的實現,用抽象工廠可以保證創建的元件實例保持平臺一致。實際上,抽象工廠中的方法一般都是工廠方法。 | ||
|
||
### Builder 生成器 | ||
|
||
生成器可用於逐步構建對象,每步構建一部份。適用於構建複雜的對象。 | ||
|
||
### Factory Method 工廠方法 | ||
|
||
工廠方法与構造函數類似,都是實例化類型的方式。時常不知該用工廠方法還是構造函數,因為大多數時候一個類只有一個創建實例的方法,用哪個沒甚麼區別。_Effective Java_ 的建議是——儘量使用工廠方法。 | ||
|
||
### Prototype 原型 | ||
|
||
原型模式「創建」新實例的方法是**複製**事先準備好的「原型」對象。這個方法比較有趣,之前並沒有想到還能這樣利用複製,因為複製(Clone)很麻煩,_Effective Java_ 中建議謹慎使用。書中指出,原型模式對於 C++ 這類「類型」本身並不是對象的語言特別有用;而對於「類型也是對象」的語言,如 Smalltalk 或 Object C,就不那麼有用了。 | ||
|
||
### Singleton 單例 | ||
|
||
單例模式保證一個類型只能有一個實例,比較實用。關於 Java 中實例的創建方式,[維基百科](https://en.wikipedia.org/wiki/Singleton_pattern#Example)里有詳細的描述。個人推薦使用枚舉類型的方式,簡單安全。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters