每个人都过得愉快。
我有一个带有runRandomExercise()方法的抽象类,以及几个扩展它的类来添加不同类型的练习。
我现在想要选择一个随机类型的练习,所以我需要随机选择其中一个类,并在其上调用runRandomExercise()。
现在我手动编码,这不是我认为最好的解决方案。但是,由于类类型不同,我不能只存储数组中的类,如果我使用object [],则无法调用runRandomExercise()方法。有任何聪明的方法来处理这个问题吗?
这是我的代码,直到现在。它有效,但添加其他类会很痛苦......
/*Specific classes that extend abstract class TrainingClass with the runRandomExercise() method*/
private MatheMagic mMathMag;
private Mnemonics mMnemonics;
private String[] mTrainingClasses;
/*Initialize classes*/
mMathMag = new MatheMagic();
mMnemonics = new Mnemonics();
/*Manually store classe names*/
mTrainingClasses = new String[2];
mTrainingClasses[0] = "mMathMag";
mTrainingClasses[1] = "mMnemonics";
/*Return random exercise*/
public String[] RandomExercise() {
Random aGenerator = new Random();
/*Get random class name*/
int rnd = aGenerator.nextInt(mTrainingClasses.length);
String aChosen = mTrainingClasses[rnd];
String[] aRes = new String[2];
if (aChosen == "mMathMag") {
aRes = mMathMag.runRandomExercise();
} else if (aChosen == "mMnemonics") {
aRes = mMnemonics.runRandomExercise();
}
return aRes;
}
EDIT 以下是TrainingClass的定义方式:
/** Common interface for all exercises */
public interface Exercise {
public String[] run();
}
/** Common interface for all training classes */
public abstract class TrainingClass {
private Random mRandGen = new Random();
public ArrayList<Exercise> mExerciseTypes = new ArrayList<Exercise>();
/** Run a random exercise */
public String[] runRandomExercise() {
int i = mRandGen.nextInt(mExerciseTypes.size());
return mExerciseTypes.get(i).run();
}
}
/*Specific training class*/
public class MatheMagic extends TrainingClass {
public MatheMagic() {
class SomeExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 1";
mRes[1] = "Answer type 1";
return mRes;
}
}
class SomeOtherExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 2";
mRes[1] = "Answer type 2";
return mRes;
}
}
SomeExercise mN = new SomeExercise();
SomeOtherExercise mS = new SomeOtherExercise();
mExerciseTypes.add(mN);
mExerciseTypes.add(mS);
}
}
答案 0 :(得分:4)
简单的解决方案是使用通用方法创建一个接口,并让所有类扩展它。
创建该类型的集合或数组而不是Object;你可以简单地迭代或随机选择并调用你想要的方法。
感觉就像从GoF到我的命令模式。
public interface Exercise {
void execute();
}
现在你的课程会这样做:
public class MatheMagic implements Execise {
public void execute() {
// special logic here.
}
}
然后你可以这样做:
int numExercises = 1;
Exercise [] exercises = new Exercise[numExercises];
exercises[0] = new MatheMagic();
for (Exercise exercise : exercises) {
exercise.execute();
}
答案 1 :(得分:1)
是的,是的,您可以将所有这些类存储在一个数组中,然后随机调用它们。怎么样?创建一个接口,并在所有类中从该接口派生。这样您就可以基于接口调用,而不是基于实现调用。