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 类对象。任何人都可以帮我编写这个代码——就像工厂和具体类之间不应该有任何直接关系,以便注册将保留在工厂类之外,我应该得到我请求的正确的具体类对象?
谢谢巴拉吉