需要为不同的机器(例如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语句。这看起来像是多态性或工厂用例,但希望听取其他人对此是否有意见
最佳答案
看一下基于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);