01簡單工廠模式SimpleFactory
阿新 • • 發佈:2018-05-13
out div actor 以及 缺點 tor 由於 創建型 實例
一、什麽是簡單工廠模式
簡單工廠模式屬於類的創建型模式,又叫做靜態 工廠方法模式。通過專門定義一個類來負責創建 其他類的實例,被創建的實例通常都具有共同的 父類。
二、模式中包含的角色及其職責
1.工廠(Creator)
角色簡單工廠模式的核心,它負責實現創建所有實例的內部邏輯。工廠類可以被外界直接調用,創建所需的產品對象。
2.抽象(Product)角色
簡單工廠模式所創建的所有對象的父類,它負責描述所有實例所共有的公共接口。
3.具體產品(Concrete Product)
角色簡單工廠模式所創建的具體實例對象
三、簡單工廠模式的優缺點
在這個模式中,工廠類是整個模式的關鍵所在。它包含必要的判斷 邏輯,能夠根據外界給定的信息,決定究竟應該創建哪個具體類的 對象。用戶在使用時可以直接根據工廠類去創建所需的實例,而無 需了解這些對象是如何創建以及如何組織的。有利於整個軟件體系 結構的優化。
不難發現,簡單工廠模式的缺點也正體現在其工廠類上,由於工廠類集中 了所有實例的創建邏輯,所以“高內聚”方面做的並不好。另外,當系統中的 具體產品類不斷增多時,可能會出現要求工廠類也要做相應的修改,擴展 性並不很好。
蘋果類
1 public class Apple implements Fruit{2 /* 3 * 采集 4 */ 5 public void get(){ 6 System.out.println("采集蘋果"); 7 } 8 }
香蕉類
1 public class Banana implements Fruit{ 2 /* 3 * 采集 4 */ 5 public void get(){ 6 System.out.println("采集香蕉"); 7 } 8 }
水果類
1 public interface Fruit {2 /* 3 * 采集 4 */ 5 public void get(); 6 }
水果工廠
1 public class FruitFactory { 2 // /* 3 // * 獲得Apple類的實例 4 // */ 5 // public static Fruit getApple() { 6 // return new Apple(); 7 // } 8 // 9 // /* 10 // * 獲得Banana類實例 11 // */ 12 // public static Fruit getBanana() { 13 // return new Banana(); 14 // } 15 /* 16 * get方法,獲得所有產品對象 17 */ 18 public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException { 19 // if(type.equalsIgnoreCase("apple")) { 20 // return Apple.class.newInstance(); 21 // 22 // } else if(type.equalsIgnoreCase("banana")) { 23 // return Banana.class.newInstance(); 24 // } else { 25 // System.out.println("找不到相應的實例化類"); 26 // return null; 27 // } 28 Class fruit = Class.forName(type); 29 return (Fruit) fruit.newInstance(); 30 } 31 }
測試方法
1 public class MainClass { 2 public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { 3 // //實例化一個Apple 4 // Apple apple = new Apple(); 5 // //實例化一個Banana 6 // Banana banana = new Banana(); 7 // 8 // apple.get(); 9 // banana.get(); 10 11 // //實例化一個Apple,用到了多態 12 // Fruit apple = new Apple(); 13 // Fruit banana = new Banana(); 14 // apple.get(); 15 // banana.get(); 16 17 // //實例化一個Apple 18 // Fruit apple = FruitFactory.getApple(); 19 // Fruit banana = FruitFactory.getBanana(); 20 // apple.get(); 21 // banana.get(); 22 23 Fruit apple = FruitFactory.getFruit("Apple"); 24 Fruit banana = FruitFactory.getFruit("Banana"); 25 apple.get(); 26 banana.get(); 27 } 28 }
01簡單工廠模式SimpleFactory