天天看點

Head First Design Patterns 讀書筆記(一)

     最近有幸閱讀O'Reilly的Head First Design Patterns,發現這本書的确是對Design Patterns的一種全新解讀,雖然影印版閱讀起來仍然不那麼流暢,但是已經讓我對Design Patterns有了進一步的認識,雖然接下來會很忙,但仍然計劃抓緊時間把這本書學習一遍,以加深自己對Design Patterns的了解。

      本書中沒有照搬其他書籍對Design  Patterns分類從工廠方式開始介紹的老套路,而是以一個程式員很常見的工作場景開始了Design Patterns的介紹和讨論(本書中介紹都是基本都是這樣的引人深入的方法)。

      截至目前(辛辛苦苦的讀了7章英文),學習到的東西在這裡做一個粗略的總結(以英文為準):

一、OO Principles:

   1.Encapsulate what varies

   2.Favor composition over inheritance

   3.Program to interfaces,not implementations 看到這個原則讓我想起James Gossing就曾經在别人采訪中說過:如果再給他一次機會重頭開發Java,那麼他将去掉所有的抽象類而采用接口實作,不過他可不是對着這個原則來的,整個Patterns中都一直在告訴我們要擁抱變化,最好的方式就是解偶,而接口就是最好的解藕方式。

   4.Strive for loosely coupled designs between objects that interact

   5.Classes should be open for extension but closed for modification

   6.Depend on abstractions.Do not depend on concrete classes

句句金句,需熟記于心,等有空的時候我再補充一些比較常見的場景以便于了解。

二、Design Toolbox

   1.Strategy - defines a family of algorithms,encapthulates each one,and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it.

   2.Observer - defines a one-to-many dependency between objects so that when one object changes state,all its dependents are notified and updated automatically.

   3.Decorator - Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality.  (最常見的就是java.io包,盡管使用Decorator可能會使程式晦澀難懂,但是它仍然是使用子類來獲得方法繼承之外的另一個穩妥的程式設計手段)

   4.Factory method - Define an interface for creation an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to the subclasses.(其中還包含一個Simple Factory,但是它并不是Patterns,而是一個可以幫助你将用戶端與指定類解偶的方法)

   5.Abstract Factory - Provide an interface for creating families of related or dependent objects without specifying their concrete classes. (Dependency Injection)

繼續閱讀