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
及其creators
对CreateMailingController
的dynamicGroupId
和staticGroupId
值一无所知。这些值是由一些用户从web界面设置的。因此,工厂无法初始化要使用这些值创建的类型的相应字段
RecipientTypesFactory
它的创造者是春豆
问题:如何以灵活的方式将dynamicGroupId
和staticGroupId
的值传递给工厂,并避免编写类似switch-case
的代码?可能吗
也许还有另外一种说法。事实上,工厂正在创建一个对象的原型
# 1 楼答案
可以使用map避免切换情况,如下所示: