這學期修完了OOAD(物件導向分析與設計)
其中有提到GRASP Pattern,這是一個滿重要的主題
所以想要把這9個Pattern整理一下分享給各位
也當作學習筆記
Pattern是什麼?
我記得我的老師Teddy曾經這麼跟我們說過:
「如果從字面上解釋,重複出現的東西、事件或現象就稱為Pattern(模式)」
在GoF的Design Pattern書中這麼說:
「A Pattern is a solution to a problem in a context
(模式是在一個情境之下,針對一個問題的解法)」
那GRASP Pattern就是定義了9個基本在設計OO的原則
GRASP的全名為:General Responsibility Assignment Software Patterns
而這9個Pattern分別為:
Creator
Controller
Pure Fabrication
Information Expert
High Cohesion
Indirection
Low Coupling
Polymorphism
Protected Variation
我們就先從Information Expert開始吧
Information Expert
Problem:
What is a general principle of assigning responsibilities to objects?
Solution:
Assign a responsibility to the information expert ─ the class that has the information
mation necessary to fulfill the responsibility.
一個應用程式會有千百個責任(responsibilities),
這裡所謂的責任可能可以說是程式的某個功能或方法
那在我們的Design Model中可能會定義百個、千個Software classes
而在這邊我們要探討的是這些責任應該是由哪個class要去實現它
Information Expert 這個Pattern就是要告訴我們如何解決這個問題
而Soluton就是把工作交給有帶著資訊的class做
這裡所謂的有帶著資訊的class可能是擁有屬性的、或是方法的類別
這邊我給大家看一個上課時陳偉凱老師給我們的範例
這邊我們可以看到在some other class 這邊他會透過foo這個類別中的GetValue()這個方法把value取出來
接著判斷value是否大於100 若大於100則打八折,如果沒超過100則只打9折
而在這邊的程式寫作方式就違反了information expert 這個pattern了
可以看到這張圖,我們把剛剛判斷的邏輯寫成一個foo類別的方法Discount()
因為value這個值本身就是foo這個類別帶有的資訊,所以我們把折扣這件事讓foo做
而其他class只需要使用到foo的Discount()方法即可
參考:
[1] Applying UML and Patterns,Third Edition,Craig Larman
[2] https://myweb.ntut.edu.tw/~wkchen/ 北科大資工系陳偉凱教授 物件導向設計與分析課程PPT