【发布时间】:2015-05-12 10:40:24
【问题描述】:
我有RecipientTypesFactory,它将创建RecipientType 类型的对象。对于RecipientTypes 对象,我有以下层次结构:
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 之类的代码?这可能吗?
也许为此目的还有另一种模式。事实上,工厂正在创建对象的原型。
【问题讨论】:
标签: java spring design-patterns factory