簡単なステートマシンを定義しましょう:
public enum State {
A, B, C, D;
private List<State> validChange;
static {
A.validChange = Arrays.asList(B);
B.validChange = Arrays.asList(C);
C.validChange = Arrays.asList(A, D);
D.validChange = Arrays.asList(D);
}
public boolean couldChange(State newState) {
return validChange.contains(newState);
}
}
および単純な状態オブジェクト
public class StateObject {
private State currentState;
public State getCurrentState() {
return currentState;
}
public void setCurrentState(State currentState) {
if (this.currentState != null && !this.currentState.couldChange(currentState)) {
throw new IllegalStateException(String.format("Can not change from %s to %s", this.currentState, currentState));
}
this.currentState = currentState;
}
}
セッターに見られるように、状態の変更が有効であることを確認します。私の質問:
- セッターメソッドにいくつかのロジックを追加するのは良い解決策ですか?
- いつロジックを追加すべきか、いつ追加すべきでないか?
- そうでなければ、なぜですか?