【发布时间】:2021-10-16 01:56:24
【问题描述】:
我有一个类,里面有一个方法,负责根据特定条件处理模板
public doProcessing(@RequestParam("tempId") int TempId){
if(tempId == 1){
//some logic
}
elseIf(tempId == 2){
// another type of logic
}
elseIf(tempId == 3){
// some more complex type of logic
}
}
每周都会出现一个新模板,我必须添加这个 if-else
不,我的问题是根据SOLID原则开闭原则,类是对扩展开放,对修改关闭。
所以我可以根据新的 if-else 条件添加新逻辑吗?
这是我的完整代码
public interface TemplateClassification {
QuesObj processTemplate();
}
public class Template1 implements TemplateClassification{
@Override
public QuesObj processTemplate() {
return new QuesObj("Hi I am header 1","Hi I am footer 1");
}
}
public class Template2 implements TemplateClassification{
@Override
public QuesObj processTemplate() {
return new QuesObj("Hi I am header 2","Hi I am footer 2");
}
}
public class TemplateInfo {
private TemplateClassification templateClassification;
public TemplateClassification getTemplateClassification() {
return templateClassification;
}
public void setTemplateClassification(TemplateClassification templateClassification) {
this.templateClassification = templateClassification;
}
}
public class TemplateProduct {
public QuesObj calculateTemplate(TemplateInfo templateInfo){
QuesObj ques = templateInfo.getTemplateClassification().processTemplate();
return ques;
}
}
@RestController
class Pg {
@Autowired
TemplateInfo templateInfo;
@Autowired
TemplateProduct templateProduct;
public doProcessing(@RequestParam("tempId") int TempId){
QuesObj ques = null;
if(tempId == 1){
Template1 temp = new Template1();
ques = templateProduct.calculateTemplate(templateInfo);
}
elseIf(tempId == 2){
Template2 temp = new Template2();
ques = templateProduct.calculateTemplate(templateInfo);
}
elseIf(tempId == 3){
// coming soon
}
}
}
我应该使用Class.forName,然后为其创建新实例吗?
Class c = Class.forName("ocp."+state);
TemplateClassification ref = (TemplateClassification)c.newInstance();
【问题讨论】:
标签: java open-closed-principle