我们可以修改此做一个简单的引擎
public interface Function<T> {
T operate(Map<String,T> values);
}
public class Calculation<T> {
private Map<String,T> values;
private Function<T> function;
public Calculation(Map<String,T> values, Function<T> function) {
this.values = new HashMap<String,T>(values);
this.function = function;
}
public T calculate() {
return function.operate(Collections.unmodifiableMap(values));
}
// assume setters and getters are in place to manipulate the backing map and the functor object
}
有了这个地方,我们可以定义各种功能和计算
public static void main(String[] args) {
Function<Integer> original = new Function<Integer>() {
public Integer operate(Map<String,Integer> values) {
// these will throw exceptions if they don't exist, which is desired
// granted it's NullPointerException instead of IllegalStateException, but close enough for this example
int age = values.get("age").intValue();
int height = values.get("height").intValue();
int fights = values.get("fights").intValue();
return (age+height)*fights;
}
};
Map<String,Integer> map = new Map<String,Integer>();
map.put("age",10);
map.put("height",100);
map.put("fights",25);
Calculation<Integer> calc = new Calculation<Integer>(map,original);
// later someone can replace either the values in the backing map
// or replace the function altogether to get a new function
}
当您试图使它不仅在问题出现用户定义,但用户输入。如在中,用户可以将该功能定义为您预先输入的一组功能之一。在这种情况下,你需要有一个解析器,原来是这样的:
value + (other + (something * that))/wazook
到这一点:
EquationBuilder<Integer> eb = new EquationBuilder<Integer>();
eb.append(map.get("value"));
eb.append(OPERATOR.PLUS);
// etc
return eb.evaluate();
但是,这可能超出你的任务的范围。或者,也许不是。
希望这比我以前的例子更接近您的要求。
问题辉光编码器是公式是用户定义的,所以它可以是任何数量的大小和任何公式我是做这个没有类的部分... –
@ashleysmith我修改了我的答案,以满足我对您的需求的重新评估。这种方法将如何为你工作? – corsiKa