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