需要为resetCredentialsMachineOne
,resetCredentialsMachineTwo
等不同的计算机实例化多个PauseTransition个实例。对于每台机器,将重复PauseTransition
实例创建代码,如下所示。 expireCredentialsForMachine()
重置Credentials
对象,以便强制用户重新登录:
resetCredentialsMachineOne = new PauseTransition(Duration.minutes(2));
resetCredentialsMachineOne.setOnFinished(e -> expireCredentialsForMachine(machineOne));
resetCredentialsMachineTwo = new PauseTransition(Duration.minutes(2));
resetCredentialsMachineTwo.setOnFinished(e -> expireCredentialsForMachine(machineTwo));
.....
当用户登录时,每个conditional
个实例都会有以下PauseTransition
代码:
if(machineOneLogsIn)
resetCredentialsMachineOne.playFromStart();
else if(machineTwoLogsIn)
resetCredentialsMachineTwo.playFromStart();
...
寻找一种以更好的方式设计代码的方法,而不是拥有大量的if语句。这似乎是一个多态或工厂用例,但是如果他们对此有任何意见,他们希望听取他人的意见
答案 0 :(得分:2)
不确定您的应用程序是如何设计的,我个人会设计如下:
public class Machine {
private final PauseTransition resetCredentials = new PauseTransition(Duration.minutes(2));
public Machine() {
resetCredentials.setOnFinished(e -> expireCredentials());
}
public final void logIn() {
resetCredentials.playFromStart();
}
public final void expireCredentials() {
// Your implementation
}
// Other things that you may need, e.g. credentialsExpired boolean field
}
为什么这是有道理的:
PauseTransition
进行凭据有效性倒计时。不是打破所有这些事情并试图混合和匹配,而是将它们移动到一个共同的类中更容易。无论这个类是模型还是控制器,它都取决于你从这里修改的方式。您可以将状态移动到另一个模型类中,并让逻辑保留为控制器。
答案 1 :(得分:2)
根据SOLID原则查看以下课程。
public class MachinePauseTransitionManager {
private static final Map<Machine, PauseTransition> MACHINE_PAUSE_TRANSITIONS = new HashMap<> ();
public void createPauseTransition(Machine machine) {
PauseTransition resetCredentialsMachine = new PauseTransition(Duration.minutes(2));
resetCredentialsMachine.setOnFinished(e -> expireCredentialsForMachine(machine));
MACHINE_PAUSE_TRANSITIONS.put(machine, resetCredentialsMachine)
}
public void login(Machine machine) {
MACHINE_PAUSE_TRANSITIONS.get(machine).playFromStart();
}
}
使用方法:
MachinePauseTransitionManager manager = new MachinePauseTransitionManager();
Machine machineOne = ..
Machine machineTwo = ..
// creating pause transitions
manager.createPauseTransition(machineOne);
manager.createPauseTransition(machineTwo);
.
.
.
// when perticular machine logs in
manager.login(machineOne);
manager.login(machineTwo);
答案 2 :(得分:0)
使用枚举可以轻松实现。
从:
if(machineOneLogsIn)
resetCredentialsMachineOne.playFromStart();
else if(machineTwoLogsIn)
resetCredentialsMachineTwo.playFromStart();
为:
enum LoginType {
MachineOneLogsIn
{
@Override
public void playFromStart() {
...
}
},
MachineTwoLogsIn
{
@Override
public void playFromStart() {
...
}
};
public abstract void playFromStart();
}
method doPlay(LoginType type){
type.playFromStart()
}
让我知道这是有道理的......