【发布时间】:2015-10-08 08:48:01
【问题描述】:
Java 7
我有如下界面:
public interface SqlOperator{
public String apply(Object o);
/**
* @return an operator representing the set defined
* by inversing the image of {@this operator}.
*/
public SqlOperator not();
//Some other methods
}
我有一些类似的实现:
public class Foo implements SqlOperator{
public SqlOperator not(){
return new Foo(){
@Override
public String apply(Object o){
return String.format("NOT (%s)", super.apply(o));
}
};
}
//other methods implementation
}
还有这个
public class Bar implements SqlOperator{
public SqlOperator not(){
return new Bar(){
@Override
public String apply(Object o){
return String.format("NOT (%s)", super.apply(o));
}
};
}
//other methods implementation
}
问题是 not() 方法对于现在的所有实现几乎相同(目前我有 7 个),除了要使用 new 运算符实例化的类。有没有办法在我需要实现SqlOperator 的任何时候避免编写这样的样板代码。
【问题讨论】:
-
你用的是什么java版本?
-
我可以建议
not(foo)比foo.not()更好的API - 使用组合来构建你的表达式会更好。它还使实现and或or运算符更容易:and(foo, bar)而不是foo.and(bar)等。这意味着您的SqlOperator接口将只包含apply方法。 -
@AndyTurner 好吧,我考虑过了。但是 not 方法是特定于操作符的。
标签: java code-reuse anonymous-class