工廠方法模式

工廠方法模式

工廠方法模式在簡單工廠模式的基礎上,爲每一個具體產品類提供一個對應的工廠類,每一個工廠類實現工廠接口定義的公共方法建立具體的對象。工廠模式中角色包括:產品接口、產品類、工廠接口和工廠類。工廠模式經過多態實現,又稱爲多態工廠模式。客戶端經過調用每一個產品類對應的產品工廠來建立對象實例,一樣是將對象建立和對象使用分離開來了。app

解決的問題

1)簡單工廠模式使用一個靜態工廠方法建立全部產品,一旦這個工廠方法出現問題,全部的客戶端(使用各個產品類的類)都會受到影響,工廠方法模式經過爲每一個產品類定義工廠方法建立產品避免了這種問題。ide

2)雖然引入了反射機制的簡單工廠模式能夠避免引入新產品時修改工廠方法,知足開閉原則,不過若是各產品類實例的初始化方法都不相同,勢必又要添加邏輯判斷,使這個工廠方法巨大無比,工廠方法模式經過爲每一個產品類定義工廠方法建立產品避免了這種問題。ui

工廠方法模式類圖

以Fruit爲產品接口,Apple、Orange和Banana是具體產品類,Factory是工廠接口,AppleFactory、OrangeFactory、BananaFactory是具體產品對應的工廠類。FactoryPattern是客戶端。spa

具體實現

工廠方法模式的具體實現以下:code

 1 public class FactoryPattern {
 2     public static void main(String[] args){
 3         IFactory fac=new AppleFactory();
 4         Fruit2 fru1=fac.createProduct();
 5         fru1.eat();
 6         IFactory fac2=new OrangeFactory();
 7         Fruit2 fru2=fac2.createProduct();
 8         fru2.eat();
 9         IFactory fac3=new BananaFactory();
10         Fruit2 fru3=fac3.createProduct();
11         fru3.eat();
12     }
13 }
14 interface Fruit2{
15     public abstract void eat();
16 }
17 
18 class Apple2 implements Fruit2{
19     public void eat(){
20         System.out.println("factory method pattern,eat apple");
21     }
22 }
23 class Orange2 implements Fruit2{
24     public void eat(){
25         System.out.println("factory method pattern,eat orange");
26     }
27 }
28 class Banana2 implements Fruit2{
29     public void eat(){
30         System.out.println("factory method pattern,eat banana");
31     }
32 }
33 interface IFactory{
34     public abstract Fruit2 createProduct();
35 }
36 class AppleFactory implements IFactory{
37     public Fruit2 createProduct(){
38         return new Apple2();
39     }
40 }
41 class BananaFactory implements IFactory{
42     public Fruit2 createProduct(){
43         return new Banana2();
44     }
45 }
46 class OrangeFactory implements IFactory{
47     public Fruit2 createProduct(){
48         return new Orange2();
49     }
50 }
View Code

優勢

1)系統中添加新產品時,只須要添加對應的產品類和工廠類,相比於簡單工廠模式中須要修改靜態工廠的作法,更加符合開閉原則。對象

2)每一個具體工廠類單獨負責建立具體產品,既知足了不一樣產品初始化不一樣的狀況,又避免了工廠方法出現問題致使系統中全部客戶端收到影響的狀況。blog

缺點

1)添加新產品時,須要同時添加產品類和對應的工廠類,當產品數量過多時,會增長系統的複雜度接口

2)在客戶端裏須要更換爲另外一種產品時,仍然須要修改實例化的具體工廠。get

3)一個具體工廠只能建立一中具體產品。產品

參考:

http://www.jasongj.com/design_pattern/factory_method/ 

相關文章
相關標籤/搜索