Guice(發音同 juice)是 Google 所內部使用的 Java Dependency Injection framework,剛看到這個消息,它已經以 open source 型態釋出。
如果你有用過 Spring framework,那你應該已經知道什麼是 Dependency Injection - (DI) (或者稱 Inversion of Control - IoC)。DI 是一種 pattern,它的基本精神是:
如果 A object 有與 B object 的相依性,則應該利用 interface, setter 或 constructor 的方式將 B object 注入 A object 而不是在 A object 裡直接產生一個 B object instance。
比方說我們有個 Document class,其中有個 store() method 用來儲存資料:
class Document { ... public void store() { Floppy f = new Floppy(); f.store(this); } }
這樣我們可以看出 Document class 是相依於 Floppy 這個 class 的,但這樣的設計將兩個 class 的相依性綁得太緊,也讓 Document class 的彈性降低,比方說,你想改變成其它的儲存媒體,那還得去改寫 Document 這個 class。
如果我們利用 DI 中Type 1-利用 interface 方式注入相依性-來改寫的話:
interface Storable { public void createStorage(IStorage storageObject); } class Document implements Storable { ... private IStorage storage; ... public void createStorage(IStorage storageObject) { this.storage = storageObject; } ... public void store() { this.storage.store(this); } }
讓 Document 實作一個 interface ,藉此實作一個 method 來建立與儲存媒體的相依性。這樣的寫法,便能夠在 Document object 呼叫 createStorage 的時候瞭解到它該儲存到哪裡去。
而 DI 的Type 2-利用 setter -很類似 Type 1 ,大概會是這樣:
class Document { private IStorage storage; ... public void setStorage(IStorage storageObject) { this.storage = storageObject; } public void store() { this.storage.store(this); } }
最後再介紹 Type 3 -利用 constructor 注入-:
class Document { private IStorage storage; ... public Document(IStorage storageObject) { this.storage = storageObject; } ... public void store() { this.storage.store(this); } }
Guice 的特色是它完全使用 Java 5 的一些新技術,如:Annotation、Generics 等等,同時也增加了許多新的 features:
- Guice empowers dependency injection.
- Guice cures tight coupling.
- Guice enables simpler and faster testing at all levels.
- Guice reduces boilerplate code.
- Guice is type safe.
- Guice externalizes configuration when appropriate.
- Guice lets you compose your application of components which are truly independent.
- Guice reports error messages as if they will be read by human beings.
- Guice is small and very fast.
Guice 的 leader 說 Guice 的發明是為了讓寫 Java 的人寫少一點 code,更重要的是能讓一個剛接下幾百萬行 code 的人能夠維護他,看來 Guice 是相當值得一試的 framework!
歷史上的今天
- [預告] HappyDesigner 聚會 - 2008
文章分類:
標籤:

