我正在尝试编写工厂模式以在我的程序中创建MainMode或TestMode.我以前用来创建这些对象的代码是:
play = (isMode) ? new MainMode(numberRanges, numberOfGuesses) :
new TestMode(numberRanges, numberOfGuesses, randNo());
Run Code Online (Sandbox Code Playgroud)
我的游戏(游戏)将根据布尔值(isMode)创建MainMode对象或TestMode对象.正如您所看到的,我在TestMode对象中添加了一个额外的值(randNo()).此值在TestMode中用于允许用户输入自己的"随机数",而在MainMode构造函数中,这是随机生成的.在这个程序中,MainMode和TestMode都是抽象类Game的子类.
现在我想用工厂模式替换这一行,虽然我不确定我的TestMode构造函数需要一个额外的对象,我不确定我需要传递这个值的位置.如果我要创建一个工厂,它需要在一个新的类中,可能名为GameFactory或ModeFactory或类似的东西.
我该怎么做?
编辑:这里的问题是上面的代码在我的GUI中,其中numberRanges,numberOfGuesses和randNo()方法的值是.我想创建一个Factory类,但我无法传递这些值,因为randNo()会激活它自己.这是我的randNo()方法.
private int randNo() {
boolean isValidNumber = true;
int testRandomNum = 0;
while(isValidNumber) {
try {
testRandomNum = Integer.parseInt(JOptionPane.showInputDialog("Enter Random Number"));
isValidNumber = false;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Sorry, but the number you entered was invalid");
}
}
return testRandomNum;
}
Run Code Online (Sandbox Code Playgroud)
问题是每当我传递randNo()时它都会显示JOptionPane.正如我已经说过的,GUI和Logic是分开的.GUI位于GUI包中,而其余代码位于逻辑包中.
我试图想出一个解决方案,根据消息类型,在运行时选择处理"消息"的类.我知道我可以使用这样的东西
if msg_type = "A"
MsgAProcessor.execute(message);
else if msg_type = "B"
MsgBProcessoror = execute(message);
....
....
....
Run Code Online (Sandbox Code Playgroud)
我不想使用上面的方法,因为我不希望代码知道我可以处理的消息类型的任何信息.我希望将来能够为新的消息类型添加新的消息处理器.我现在想到的解决方案如下
目前有3个消息处理器
MsgAProcessor
MsgBProcessor
MsgBProcessor
Run Code Online (Sandbox Code Playgroud)
所有这三个类都有一个名为execute的方法,它将以自己的方式处理消息.我创建了一个名为MsgProcessor的接口,并在接口中添加了execute()方法.
现在我很难知道调用者应该调用哪个消息处理器而不必检查消息类型.例如,我不能这样做
MsgProcessor proc = new MsgAprocessor()proc.execute()
上面将要求在if语句中,因为它需要在找到消息类型后立即调用.我还想避免使用实现类类型进行实例化.
有没有更好的方法来实现同样的目标?
我希望能够从接口调用MsgProcessor.execute,并让运行时环境知道要根据消息类型调用哪个实现类.