Factory class 应该是单例还是静态方法?

Factory class should be singleton or static method?

我制作了一个 class 来创建各种实例。这就像一个工厂。 据我所知,工厂 class 是单例或将实例创建为静态方法。 但我的 class 是 spring 原型范围。它有成员变量。还有一些方法必须调用序列 在每个方法调用后设置成员变量。

我想知道在这种情况下它是如何设计的。 你能推荐更好的方法或好的命名吗?

我正在研究 spring 框架和 java 8..

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FruiteFactory {

    private String type;
    @Setter
    private Integer field;  // set alfter call appleSupplier

    public FruiteFactory(String type) {
        Assert.notNull(type) ;
        this .type = type ;
    }

    public < T> T create(Class<T > clazz) {
        Object result;
        if (clazz == Apple.class) {
            result = appleSupplier.get();
        } else if (clazz == Banana. class) {
            result = bananaSupplier.get();
        } else {
            throw new IllegalArgumentException();
        }
        return (T ) result;
    }

    private Supplier<Apple> appleSupplier = () -> {
        Apple apple = new Apple();
        // ...
        return apple;
    };

    private Supplier<Banana> bananaSupplier = () -> {
        Banana banana = new Banana();
        banana.setField(field);
        return banana;
    };
}


@Service
public class FruiteService {
    @Autowired ApplicationContext context;

    public void buy(String type) {
        FruiteFactory fruiteFactory = context.getBean(FruiteFactory.class, type);

        Apple apple = fruiteFactory.create(Apple.class);
        // save the apple

        Integer no = apple.getNo();
        fruiteFactory.setField(no);

        Banana banana = fruiteFactory.create(Banana.class);
        // ....

    }
}

如果你真的需要根据他们的 class 名称创建水果(在一般情况下我不建议这样做),你应该只使用 Map<Class<?>, Supplier<?>> 然后使用 Class.cast return 正确的类型。

此外,您的工厂包含一个仅用于生产苹果的田地,这听起来非常错误。这个字段绝对应该被苹果的 Supplier 括起来。