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類之外,我應該得到我要求的適當的具體類對象?工廠模式的例子 - 需要解決下面的代碼
感謝 巴拉吉
「我得到空指針」:其中,由什麼引起的? – Raedwald