gpt4 book ai didi

java - 如何将参数传递到工厂以创建对象?

转载 作者:行者123 更新时间:2023-11-30 03:26:02 28 4
gpt4 key购买 nike

我有RecipientTypesFactory这将创建 RecipientType 类型的对象。对于 RecipientType s 对象我有以下层次结构:

public interface RecipientType{
public abstract Object accept(RecipientTypeVisitor v);
}

public class DynamicGroupType implemetns RecipientType{

private Integer dynamicGroupId;

public Object accept(RecipientTypeVisitor visitor){
return visitor.visit(this);
}
//GET, SET
}

public class StaticGroupType implements RecipientType{

private Integer staticGroupId;

public Object accept(RecipientTypeVisitor visitor){
return visitor.visit(this);
}
//GET, SET
}

RecipientTypesFactory它本身看起来如下:

public enum RecipientTypeEnum {
STATIC_GROUP, DYNAMIC_GROUP
}

public class RecipientTypesFactory{
private Map<RecipientTypeEnum, RecipientTypeCreator> creators;

public RecipientType createRecipientType(RecipientTypeEnum t){
return creators.get(t).create();
}
}

我不会提供 RecipientTypeCreator 的实际定义及其层次结构,因为我认为它不是很重要。

现在我有了 Controller :

public class CreateMailingController{
private RecipientTypesFactory recipientTypesFactory;
private Integer dynamicGroupId;
private Integer staticGroupId;
private RecipientTypeEnum selectedType;

//GET, SET, other staff

public void createMailing(){
Type t = recipientTypesFactory.createRecipientType(selectedType);
//How to initialize t's field with an appropriate value?
}
}

事情是RecipientTypesFactory及其 creators一无所知CreateMailingControllerdynamicGroupIdstaticGroupId值(value)观。这些值是由某些用户通过网络界面设置的。因此工厂无法初始化要使用这些值创建的类型的相应字段。

RecipientTypesFactory它的创造者是 Spring Bean 。

问题:我如何传递 dynamicGroupId 的值和staticGroupId灵活到工厂,免写信switch-case喜欢代码?这可能吗?

也许还有另一种说法可以达到这个目的。事实上工厂正在创建一个对象的原型(prototype)。

最佳答案

您可以使用 map 来避免切换情况,如下所示:

private static final Map<String, RecipientType> factoryMap = Collections
.unmodifiableMap(new HashMap<String, RecipientType>() {
{
put("dynamicGroupId", new RecipientType() {
public RecipientType accept() {
return new DynamicGroupType();
}
});
put("staticGroupId", new RecipientType() {
public RecipientType accept() {
return new StaticGroupType();
}
});
}
});

public RecipientType createRecipientType(String type) {
RecipientType factory = factoryMap.get(type);
if (factory == null) {

}
return factory.accept();
}

关于java - 如何将参数传递到工厂以创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30188420/

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