gpt4 book ai didi

java - 在java中随机选择的对象上调用通用方法的更好方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:52:44 27 4
gpt4 key购买 nike

祝大家今天愉快。

我有一个带有方法 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;
}

编辑以下是 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);
}

}

最佳答案

简单的解决方案是使用通用方法创建一个接口(interface),并让您的所有类扩展它。

创建该类型的集合或数组而不是对象;您可以简单地遍历或随机选择并调用您想要的方法。

给我的感觉就像是 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();
}

关于java - 在java中随机选择的对象上调用通用方法的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com