我有以下课程
public class MyCustomFactory extends SomeOther3rdPartyFactory {
// Return our custom behaviour for the 'string' type
@Override
public StringType stringType() {
return new MyCustomStringType();
}
// Return our custom behaviour for the 'int' type
@Override
public IntType intType() {
return new MyCustomIntType();
}
// same for boolean, array, object etc
}现在,例如,自定义类型类:
public class MyCustomStringType extends StringType {
@Override
public void enrichWithProperty(final SomePropertyObject prop) {
super.enrichWithProperty(prop);
if (prop.getSomeAttribute("attribute01")) {
this.doSomething();
this.doSomethingElse();
}
if (prop.getSomeAttribute("attribute02")) {
this.doSomethingYetAgain();
}
// other properties and actions
}
}但每个自定义类型类(如上面的字符串)可能具有完全相同的if (prop.getSomeAttribute("blah")) { // same thing; }
假设我要添加另一个属性,有没有一种很好的方法可以避免在每个需要它的自定义类型类中复制if语句?我可以将每个if语句移到实用程序类中,但我仍然需要将调用添加到实用程序类中的方法。我想我们可以做得更好。
发布于 2018-03-03 00:31:44
您可以创建Map<String, Consumer<MyCustomStringType>>,其中键是属性名,值是方法调用。
public class MyCustomStringType extends StringType {
private final Map<String, Cosnumer<MyCustomStringType>> map = new HashMap<>();
{
map.put("attribute01", o -> {o.doSomething(); o.doSomethingElse();});
map.put("attribute02", MyCustomStringType::doSomethingYetAgain);
// other properties and actions
}
@Override
public void enrichWithProperty(final SomePropertyObject prop) {
super.enrichWithProperty(prop);
map.entrySet().stream()
.filter(entry -> prop.getSomeAttribute(entry.getKey()))
.forEach(entry -> entry.getValue().accept(MyCustomStringType.this));
}
}根据初始化这个类的方式(以及这个映射是否总是相同的),您也许能够将其转化为静态的最终不可变映射。
我还建议给它起个更好的名字,但这里有很多东西取决于你的域以及这个map和循环的实际作用。
https://stackoverflow.com/questions/49073228
复制相似问题