I have a tree of boolean operations from a boolean expression that I have to run in Java. The tree would be something like this: And I would need to run it in Java iteratively so that it returns me a boolean value.
boolean b = AND(isNumberEven("4"), AND(isNumberOdd("7"), isNumberEven("6"))
问题是我需要编写接口,因为在我的公司中,我们可以创建许多类,比如和,或者,hasIn数组(它可以是其他开发人员需要的任何属性).我们通常有两种类型的 node :逻辑 node ,它有两个分支;属性判断 node ,它是树的叶子.
下面我想做的是一些我认为在Java中非常错误的事情,请帮助我正确地做好它.
我的 idea 是创建两个接口,一个用于逻辑运算符,另一个用于属性判断.属性判断器需要从输入计算它的属性,而逻辑运算符需要计算两个分支,然后用两个结果计算一些东西(比如AND或OR,我们现在不关心NOT运算符).我在考虑做这些界面
class PropertyCheckingInput {
String s; // dummy property, this object is the thing we want to verify the property on (example, if this string is an even number)
PropertyCheckingInput(...){...} // constructor for all params
}
interface PropertyChecking {
boolean fire(PropertyCheckingInput i);
}
class LogicOperatorInput<
T extends LogicOperator or PropertyChecking, // it can be one or the other
Ti extends LogicOperatorInput or PropertyCheckingInput
> {
T left;
Ti leftInput;
T right;
Ti rightInput;
// probabily the type of leftInput should act accordingly to the type of left, but I don't know how to enforce this in Java with generics
LogicOperatorInput(...){...} // constructor for all params
}
interface LogicOperator{
boolean fire(LogicOperatorInput i);
}
在这种情况下,如果我想实现类似的东西,我可以这样做
class And implements LogicOperator {
boolean fire(LogicOperatorInput i) {
i.left.fire(i.leftInput) && i.right.fire(i.rightInput);
}
And() {}
public static void main(String[] args) {
// expression: isNumberEven("4") AND isNumberOdd("7") AND isNumberEven("6")
boolean b = new And().fire(new LogicOperatorInput(
new isNumberEven(),
new PropertyCheckingInput("4"),
new And(),
new LogicOperatorInput(
new isNumberOdd(),
new PropertyCheckingInput("7"),
new isNumberEven(),
new PropertyCheckingInput("6"))
));
System.out.println(b);
}
}
对于每个分支,我使用它们的输入执行Left和Right的函数fire,并且只关心它们的结果.然后,如果我想创建布尔表达式,我需要连接各种 node 和输入.
当然,编译器告诉我这是错误的,因为它无法推断fire()函数的正确类型.
我习惯于用Java脚本编写,它允许这种类型的东西,因为它不会判断您正在try 做什么.在Java中有没有一种方法可以做到这一点(我try 使用一些泛型或抽象类,但不起作用),或者更好的是有一种正确的方法来解决这个问题(我们有一个写成二叉树的二进制表达式,我们想通过调用与每个 node 相关联的类来解决它)?