我有以下类层次结构:
public enum Bonus{
FP,
PRECOIL,
//some ohter types
};
public interface Generator{
public Object generate();
};
public class DateGenerator implements Generator{
public String queryString;
public Integer order;
//GET, SET
public Date generate(){
//implementation
}
};
public class BonusEnumGenerator implements Generator{
public Date bonusAppliedDate;
public String description;
//GET, SET
public Bonus generate(){
//implementation
}
}
所以我需要把那些用于生成对象的参数放到一个通用对象中。
如果我创建了这个课程,它会被认为是好的,比如说GeneratorParams
并为所有Generator
的实现设置所有参数。在我的特殊情况下,我会:
public class GeneratorParams{
public String queryString;
public Integer order;
public Date bonusAppliedDate;
public String description;
}
令我讨厌的是,我把同一物体中彼此不相关的参数放在了一起。好吗?
为什么我要将所有参数放入单个对象?
Beucase我想写更多通用代码。在那种情况下,我会:
public interface Generator{
public Object generate();
public void applyParams(GeneratorParams params);
};
和applyParams
方法将针对每种类型的Generator
实施。
所以我可以这样写:
Generator g = GeneratorPrototypeFactory.createGenerator(TypeId typeId);
GeneratorParams p;
//Getting params
g.applyParams(p);
Object generated = g.generate();
我如何以更恰当的方式解决这个问题?
答案 0 :(得分:1)
简单地将GeneratorParams
设为抽象类,并将任何常见(在Date
和BonusEnum
生成器中)参数移动到:
public abstract class GeneratorParams {
public String commonParam;
//GET, SET
}
然后添加两个子类:
public class DateGeneratorParams extends GeneratorParams {
public String queryString;
public Integer order;
// GET, SET
}
public class BonusEnumGeneratorParams implements GeneratorParams {
public Date bonusAppliedDate;
public String description;
// GET, SET
}
现在在applyParam
和DateGenerator
中实施适当的BonusEnumGenerator
:
public class DateGenerator implements Generator {
public String queryString;
public Integer order;
//GET, SET
public Date generate(){
//implementation
}
@Override
public void applyParams(GeneratorParams params) throws InvalidParamException {
if(!(params instanceof DateGeneratorParams))
throw new InvalidParamException();
else
// assign values
}
}
和
public class BonusEnumGenerator implements Generator {
public Date bonusAppliedDate;
public String description;
//GET, SET
public Bonus generate() {
//implementation
}
public void applyParams(GeneratorParams params) throws InvalidParamException {
if(!(params instanceof BonusEnumGeneratorParams))
throw new InvalidParamException();
else
// assign values
}
}