I have a class that contains an Enum to do calculation. Each Enum uses some or 开发者_高级运维all of the non-static variables from the outer class. However since they can't access instance variable, I have to pass in them as parameters.
public class Outer{
ClassA a;
ClassB b;
ClassC c;
Map<MyEnum,Double> results= new EnumMap(MyEnum.class);
private enum MyEnum{
X{ public double calc(ClassA _a){ dostuff } },
Y{ public double calc(ClassB _b,ClassC _c){ dostuff } },
Z{ public double calc(ClassA _a,ClassB _b){ dostuff } };
}
public void doCalc(){
for(MyEnum item:MyEnum.values()){
result.get(item) = item.calc(...);//Not uniform here
}
}
}
My problem is that I can't have a uniform way to pass in the parameters in the for-loop. I could make each Enum method takes all classes like
public double calc(ClassA _a,ClassB _b,ClassC _c){ dostuff}
But if I have more classes, the parameter will look too ugly. Is there a better way to do this kind of thing?
Why don't you pass the instance of outer to the calc()
method. In that case, each specific enum will have the logic to deal with the Outer
object accordingly and new enums wouldn't require any change.
class Outer {
ClassA a;
ClassB b;
ClassC c;
Map<MyEnum,Double> results= new EnumMap<MyEnum, Double>(MyEnum.class);
private enum MyEnum{
X{ public void calc(Outer o){ } },
Y{ public void calc(Outer o){ } },
Z{ public void calc(Outer o){ } };
abstract void calc(Outer o);
}
public void doCalc(){
for(MyEnum item:MyEnum.values()){
item.calc(this);
}
}
}
class ClassA {}
class ClassB {}
class ClassC {}
You could change your enum method to:
public double calc(Object... params) {
switch(this) {
case X:
// cast params needed for X methodology.
// doXStuff
break;
case y:
. . .
}
}
I've noticed that you have different method implementation on the ENUM values On Java 8 you can use BiFunction:
public static class Outer {
Map<MyEnum, Double> results = new EnumMap(MyEnum.class);
public enum MyEnum {
X(defaultdoStuff1()),
Y(defaultdoStuff1()),
Z(defaultdoStuff2());
MyEnum(BiFunction<Object, Integer, Boolean> objectIntegerBooleanBiFunction) {
this.handler = objectIntegerBooleanBiFunction;
}
private BiFunction<Object, Integer, Boolean> handler;
private static BiFunction<Object, Integer, Boolean> defaultdoStuff2() {
//do stuff
return (obj, age) -> (age > 0) || obj != null;
}
private static BiFunction<Object, Integer, Boolean> defaultdoStuff1() {
//do stuff
return (obj, age) -> false;
}
}
}
精彩评论