我正在为谷歌科学博览会做一个项目。我正在制作一个应用程序,它需要两个数字(条形码和序列号),并使用各种算法将它们变成两个不同的数字(即,像费雪-叶茨洗牌)。我的代码看起来像这样:
enter code here public static void main(String[] args) {
reverseNum b = new reverseNum();
addOne c= new addOne();
plusThree f= new plusThree();
plusNine i = new plusNine();
plusTwo l = new plusTwo();
minusTwo p = new minusTwo();
plusOne r= new plusOne();
plusFour u= new plusFour();
threeTwo x= new threeTwo();
intoTwo ab= new intoTwo();
plusFive bc = new plusFive();
intoSix cd= new intoSix();
twoOne de = new twoOne() ;
plusSeven ef= new plusSeven();
plusEight fg= new plusEight();
minOne gh = new minOne();
intoSeven hi = new intoSeven();
intoEight ij = new intoEight();
intoNine jk = new intoNine();
intOne kl = new intOne();
intoFour lm = new intoFour();
// TODO code application logic here
Scanner user_input = new Scanner( System.in );
String a ;
System.out.println("Enter the Barcode:");
a = user_input.next();
System.out.println("Encrypted Barcode:"+ blah.randomMethod(a));
//Random method from the above given methods should modify this.
String z;
System.out.println("Enter the Serial Number:");
z= user_input.next();
System.out.println("Encrypted Serial Number:" + blah.randomMethod(z) );
//Random method from the above given methods should modify this
}
}
我的主要目标是用上面提到的方法(算法)修改两个给定的数字。我想要一个随机的方法从给定的列表来修改给定的数字,每次用户运行程序。我还需要把这一切到GUI。请帮助。
使用策略模式。让每个算法实现该策略的一个版本。然后使用工厂来使用您想要的任何机制获得随机策略实现。不需要将输入组合成一个对象
我同意jgitter关于策略和工厂模式的看法。
我在张贴一个例子。
public interface Algorithm {
public String execute(String input);
}
public class SomeAlgorithm implements Algorithm {
public String execute(String input) {
///... Algorithm here
}
}
public class AnotherAlgorithm implements Algorithm {
public String execute(String input) {
///... Algorithm here
}
}
public abstract class AlgorithmFactory {
public static Algorithm createRandomAlgorithm() {
//Create a new Random object
Random randomEngine = new Random();
//Retrieve a number from 0 (inclusive) to 2 (exclusive)
int randomNumber = randomEngine.nextInt(2);
//Select which implementation to use according to the random number
switch(randomNumber) {
case 0: return new SomeAlgorithm();
case 1: return new AnotherAlgorithm();
}
//This will most likely never get called, but a return value is mandatory
return null;
}
}
然后,您将检索并执行这样的算法:
String encryption = AlgorithmFactory.createRandomAlgorithm().execute(input);
请注意,工厂是抽象的,并有一个静态方法,这不是我如何处理这个问题,但它会帮助你在你的问题很好,很容易。