■ Simple Factory:
一個Simlpe Factory的功能,就是用簡單的方式,來幫助我們產出物件實體。比喻來說,一個消費者、便利超商與超商內所販售的物品,一個消費者可以去便利超商內買牙膏、飲料或是便當。如果消費者想要刷牙,需要牙膏,就會去便利商店買牙膏來刷牙,換成程式的角度來說,消費者就是一段程式碼,透過便利超商這個工廠,得到需要的物件。
我們先把焦點集中再工廠與產品的關係上,牧場是一個工廠,牧場的產品有鮮乳與優酪乳,任何人透過牧場,就可以以得到鮮乳或是優酪乳。這樣有什麼好處呢?就跟你想要喝牛奶的時候,一定是去商店買牛奶,而不是自己養一頭乳牛,想喝的時候去擠牛奶來喝吧。如果程式中有10個人,都想要喝牛奶,但也都自己養一頭乳牛,這表示程式重複的地方不是很多嗎,而且如果大家突然想要喝優酪乳,那是不是大家都要增加加工牛乳,作出優酪乳的動作嗎?我們把養牛奶跟作優酪乳的動作都集中在牧場裡,這樣不是可以減少重複的程式碼跟降低程式的複雜度。
Where Simple Factory is applied:
Simple factory is applied in may places and it is widely used, but here we will show one good place of its applications.
If you got the chance to work or examine the Enterprise Library built by microsoft, you'll notice that this concept is used. For example in Data Access Application Block of the Enterprise Library, there is class named Database (TheProduct Class), the classes is base class for SqlDatabase & OracleDatabase classes (The ProductA & ProductBclasses). Now our factory class is named DatabaseFactory (The ProductFactory class). The DatabaseFactory class has a method named CreateDatabase(string name) (CreateProduct(spec)). CreateDatabase method is responsible to create an instance of type Database, this can be SqlDatabase or OracleDatabase based on the value send in thename parameter. One this you may need to notice, is that the CreateDatabase method is static method. The developer doesn't care of which instance is returned (SqlDatabase or OracleDatabase) as long as they all have the same methods but different implementations.
參考:
http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=1281