有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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的实际定义及其层次结构,因为我认为这并不重要

现在我有了控制器:

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及其creatorsCreateMailingControllerdynamicGroupIdstaticGroupId值一无所知。这些值是由一些用户从web界面设置的。因此,工厂无法初始化要使用这些值创建的类型的相应字段

RecipientTypesFactory它的创造者是春豆

问题:如何以灵活的方式将dynamicGroupIdstaticGroupId的值传递给工厂,并避免编写类似switch-case的代码?可能吗

也许还有另外一种说法。事实上,工厂正在创建一个对象的原型


共 (1) 个答案

  1. # 1 楼答案

    可以使用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();
        }