摘要: 摘要: 原創出處: http://www.cnblogs.com/Alandre/ 泥沙磚瓦漿木匠 但願轉載,保留摘要,謝謝!html
簡單工廠模式屬於類的建立型模式,又叫作靜態工廠方法模式。經過專門定義一個類來負責建立 其餘類的實例,被建立的實例一般都具備共同的父類。java
1.工廠(Creator)角色
簡單工廠模式的核心,它負責實現建立全部實例的內部邏輯。工廠類能夠被外界直接調用,建立所需的產品對象。設計模式
2.抽象(Product)角色
簡單工廠模式所建立的全部對象的父類,它負責描述全部實例所共有的公共接口。app
3.具體產品(Concrete Product)角色
簡單工廠模式所建立的具體實例對象測試
下面咱們來個一個關於工廠類的最簡單的例子:
先給出一個接口父類 Fruit.java,而且賦予採集方法優化
public interface Fruit { /* * 採集 */ public void get(); }
隨後,有兩個實體類 Apple.java 和 Banana.javaui
public class Apple implements Fruit { /* * 採集 */ public void get() { System.out.println("採集Apples"); } }public class Apple implements Fruit { /* * 採集 */ public void get() { System.out.println("採集Apples"); } }
這樣,咱們彷彿有了原材料,簡單工廠模式,就像工廠產出商家所須要的東西。this
粗劣的版本以下:spa
public class FruitFactory { /** * 得到Apple類實例 */ public static Fruit getApple() { return new Apple(); } /** * 得到Banana類實例 */ public static Fruit getBanana() { return new Banana(); } }
升級下:.net
public class FruitFactory {/** * get方法,得到全部產品對象 * @throws IllegalAccessException * @throws InstantiationException */ public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException { if (type.equalsIgnoreCase("apple")) { return Apple.class.newInstance(); }else if (type.equalsIgnoreCase("apple")) { return Banana.class.newInstance(); }else return null; } }
在思考,究極版:
public class FruitFactory { /** * get方法,得到全部產品對象 * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ public static Fruit getFruit(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> fruit = Class.forName(type); return (Fruit)fruit.newInstance(); } }
測試下,咱們的工廠:
public class MainClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Fruit apple = FruitFactory.getFruit(Apple.class.getName()); Fruit banana = FruitFactory.getFruit(Banana.class.getName()); apple.get(); banana.get(); } }
你能夠看到打印出:
採集Apples 採集Banana
相關資料:
static Class<?>
forName(String className)
返回與帶有給定字符串名的類或接口相關聯的 Class
對象。
public T newInstance()
Creates a new instance of the class represented by this {@code Class}
public final Class<?> getClass()
返回此 Object
的運行時類。返回的 Class
對象是由所表示類的 static synchronized
方法鎖定的對象。
在這個模式中,工廠類是整個模式的關鍵所在。它包含必要的判斷 邏輯,可以根據外界給定的信息,決定究竟應該建立哪一個具體類的 對象。用戶在使用時能夠直接根據工廠類去建立所需的實例,而無 需瞭解這些對象是如何建立以及如何組織的。有利於整個軟件體系 結構的優化。不難發現,簡單工廠模式的缺點也正體如今其工廠類上,因爲工廠類集中 了全部實例的建立邏輯,因此「高內聚」方面作的並很差。另外,當系統中的 具體產品類不斷增多時,可能會出現要求工廠類也要作相應的修改,擴展 性並不很好。
來自:java設計模式
如以上文章或連接對你有幫助的話,別忘了在文章按鈕或到頁面右下角點擊 「贊一個」 按鈕哦。你也能夠點擊頁面右邊「分享」懸浮按鈕哦,讓更多的人閱讀這篇文章。