2012-09-12 113 views
1
package com.factory; 

import java.util.HashMap; 
import java.util.Map; 

//Factory class 
class FactoryClass { 
     Map products = new HashMap(); 

     void registerProduct(String prodId, ProductInt prodInterface) { 
      products.put(prodId, prodInterface); 
     } 

     ProductInt createProduct(String prodId) { 
      return ((ProductInt) products.get(prodId)).createProduct(); 
     } 
}  

// Client 
public class FactoryPattern { 
    public static void main(String[] args) { 
     FactoryClass factory = new FactoryClass(); 
     factory.createProduct("pen"); 
    } 
} 

package com.factory; 

//Interface Product 
public interface ProductInt { 
    ProductInt createProduct(); 
} 

// Concrete Product-1 
class Pen implements ProductInt { 
    static { 
     FactoryClass factory = new FactoryClass(); 
     factory.registerProduct("pen", new Pen()); 
    } 

    public ProductInt createProduct() { 
     return new Pen(); 
    } 
} 

// Concrete Product-2 
class Pencil implements ProductInt { 
    static { 
     FactoryClass factory = new FactoryClass(); 
     factory.registerProduct("pencil", new Pencil()); 
    } 
    public ProductInt createProduct() { 
     return new Pencil(); 
    } 

} 

當我運行這段代碼,我得到空指針,因爲沒有產品在HashMap中註冊。所以,當我要求產品實例爲「鉛筆」時,它找不到任何關鍵字來向我返回具體的Pencil類對象。任何人都可以幫我編碼 - 就像Factory和具體類之間不應該有任何關係,所以註冊將保持在Factory類之外,我應該得到我要求的適當的具體類對象?工廠模式的例子 - 需要解決下面的代碼

感謝 巴拉吉

+0

「我得到空指針」:其中,由什麼引起的? – Raedwald

回答

0

您正在創建的獨立實例您FactoryClass - 所有這些情況都在其中thier自己Map products實例 - 您在main()方法創建的工廠是由您創建的工廠不同,註冊您的penpencil。很明顯,在FactoryClass.products中沒有註冊的項目。

的一種方法是在你的FactoryClassstatic申報Map products - 這將解決你眼前的問題 - 即使作爲一個整體的代碼似乎需要在其他地方其他方面的改進。

0

夫婦的問題:

首先,工廠方法要麼是static或不同類比類創建。因此有一個interface其唯一的方法是創建接口的實例並不合乎邏輯。 InterfaceA可創建InterfaceB的實例,或者接口爲通用的FactoryInterface<X>並創建X的實例。見番石榴的Supplier接口

舉個例子,Pen ...能不能叫Pen.createProduct(),除非你已經擁有的Pen一個實例,因爲該方法不是一成不變的。

因此,考慮到上述情況,請考慮讓您的Factory採用Producer<X>Supplier<X>創建X的實例。

其次,考慮讓你的工廠類別爲Singleton。你遇到的問題是,每個靜態初始化創建一個新的工廠實例,立即扔掉。因此,當您稍後嘗試獲取映射值時,您將從與其註冊的實例不同的實例獲取它。

最後,在類以某種方式被使用/觸摸之前,不會調用類的靜態初始化器。您需要調用PenPencil上的某些內容來調用它們的靜態初始化塊,從而註冊它們自己。

0

除了上面的答案http://www.oodesign.com/factory-pattern.html說: 我們必須確保具體的產品類在工廠要求註冊之前加載(如果它們沒有加載,他們將不會在工廠註冊並且createProduct將返回null)。爲了確保它,我們將在主類的靜態部分中使用Class.forName方法。

class Main { 

static 
{ 
    try 
    { 
     Class.forName("OneProduct"); 
     Class.forName("AnotherProduct"); 
    } 
    catch (ClassNotFoundException any) 
    { 
     any.printStackTrace(); 
    } 
} 
public static void main(String args[]) throws PhoneCallNotRegisteredException 
{ 
    ... 
} 
}