gpt4 book ai didi

java - 工厂模式示例 - 需要以下代码的解决方案

转载 作者:行者123 更新时间:2023-12-01 05:08:28 25 4
gpt4 key购买 nike

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 中没有注册任何产品。因此,当我请求“铅笔”的 Product 实例时,它找不到任何键来返回具体的 Pencil 类对象。任何人都可以帮我编码这一点 - 就像工厂和具体类之间不应该有任何直接关系一样,这样注册将保留在工厂类之外,我应该获得我请求的正确的具体类对象?

谢谢巴拉吉

最佳答案

您正在创建 FactoryClass 的单独实例 - 每个实例都有自己的 Map products 实例 - 您在 main 中创建的工厂() 方法与您创建和注册 penpencil 的工厂不同。显然,FactoryClass.products 中没有注册任何项目。

一种方法是将 FactoryClass 中的 Map products 声明为 static - 这将解决你眼前的问题 - 即使作为一个整体您的代码似乎需要在其他地方进行其他改进。

关于java - 工厂模式示例 - 需要以下代码的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12391984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com