我有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
的值传递给工厂并避免使用{{1}像代码?这可能吗?
也许还有另一种用于此目的的模式。事实上,工厂正在创建一个对象的原型。
答案 0 :(得分:2)
您可以使用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();
}