華為 eNSP 配置 wlan 中級
阿新 • • 發佈:2020-10-09
一、什麼是工廠方法模式
工廠方法模式同樣屬於類的建立型模式又被稱
為多型工廠模式 。工廠方法模式的意義是定義一個建立
產品物件的工廠介面,將實際建立工作推遲到子類當中。
核心工廠類不再負責產品的建立,這樣核心類成為一個
抽象工廠角色,僅負責具體工廠子類必須實現的介面,
這樣進一步抽象化的好處是使得工廠方法模式可以使系
統在不修改具體工廠角色的情況下引進新的產品。
二、模式中包含的角色及其職責
1.抽象工廠(Creator)角色工廠方法模式的核心,任何工廠類都必須實現這個介面。
2.具體工廠( Concrete Creator)角色具體工廠類是抽象工廠的一個實現,負責例項化產品物件。
3.抽象(Product)角色工廠方法模式所建立的所有物件的父類,它負責描述所有例項所共有的公共介面。
4.具體產品(Concrete Product)角色工廠方法模式所建立的具體例項物件
三、工廠方法模式和簡單工廠模式比較
工廠方法模式與簡單工廠模式在結構上的不同不是很明顯。工廠方
法類的核心是一個抽象工廠類,而簡單工廠模式把核心放在一個具
體類上。
工廠方法模式之所以有一個別名叫多型性工廠模式是因為具體工
廠類都有共同的介面,或者有共同的抽象父類。當系統擴充套件需要新增新的產品物件時,僅僅需要新增一個具體對
象以及一個具體工廠物件,原有工廠物件不需要進行任何修改,也
不需要修改客戶端,很好的符合了“開放-封閉”原則。而簡單工廠
模式在新增新產品物件後不得不修改工廠方法,擴充套件性不好。工廠方法模式退化後可以演變成簡單工廠模式。
以下是例項:
1 public class MainClass {2 public static void main(String[] args) { 3 //獲得AppleFactory 4 FruitFactory ff = new AppleFactory(); 5 //通過AppleFactory來獲得Apple例項物件 6 Fruit apple = ff.getFruit(); 7 apple.get(); 8 9 //獲得BananaFactory 10 FruitFactory ff2 = new BananaFactory();11 Fruit banana = ff2.getFruit(); 12 banana.get(); 13 14 //獲得PearFactory 15 FruitFactory ff3 = new PearFactory(); 16 Fruit pear = ff3.getFruit(); 17 pear.get(); 18 } 19 }
抽象工廠
1 public interface FruitFactory { 2 public Fruit getFruit(); 3 }
具體工廠
1 public class AppleFactory implements FruitFactory { 2 3 public Fruit getFruit() { 4 return new Apple(); 5 } 6 7 }
1 public class BananaFactory implements FruitFactory { 2 3 public Fruit getFruit() { 4 return new Banana(); 5 } 6 7 }
1 public class PearFactory implements FruitFactory { 2 3 public Fruit getFruit() { 4 return new Pear(); 5 } 6 }
抽象
1 public interface Fruit { 2 /* 3 * 採集 4 */ 5 public void get(); 6 }
具體產品
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 class Pear implements Fruit { 2 3 public void get() { 4 System.out.println("採集梨子"); 5 } 6 7 }