I'm trying to use the State pattern. Depending on which state the context is in, a different error message or no error message at all will be thrown. However I'm not sure if this is the right way to use exceptions. Below is code for further clarification. I purposely excluded modifiers.
class Context {
State currentState;
void changeState(State newState) {
currenState = newState;
}
void operationA() {
currentState.tryOperationA();
// do operation A
}
// some more operations all with same structure but different functionality
}
abstract class State {
Context context;
State (Context context) {
this.context = context;
}
void tryOperationA() {
throw new IllegalStateException();
}
// some more tryOperation...
}
class AllowOpAState extends State {
@Override
void tryOperationA() {
context.changeState(new AnotherState());
}
}
class AnotherState extends State {
// changes state with other operations
}
Aucun commentaire:
Enregistrer un commentaire