Skip to content

Instantly share code, notes, and snippets.

@xgbuils
Last active December 19, 2017 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgbuils/65e3b0fcf8a3d9fac7006001376c0cc5 to your computer and use it in GitHub Desktop.
Save xgbuils/65e3b0fcf8a3d9fac7006001376c0cc5 to your computer and use it in GitHub Desktop.
State Pattern with dependency injection
class ClosedGateState implements GateState {
private GateState openGateState;
public ClosedGateState() {
}
public void setOpenGateState(GateState openGateState) {
this.openGateState = openGateState
}
public GateState enter() {
return this;
}
public GateState payOK() {
return openGateState;
}
public GateState payFail() {
return this;
}
}
class Gate {
private GateState state;
public Gate(GateState state) {
this.state = state;
}
void enter() {
this.state = this.state.enter()
}
void payOK() {
this.state = this.state.payOK()
}
void payFail() {
this.state = this.state.payFail()
}
}
interface GateState {
public GateState enter();
public GateState payOK();
public GateState payFail();
}
State closedGateState = new ClosedGateState()
State openGateState = new OpenGateState()
// inject OpenGateState instance for not creating it inside of ClosedGateState class
closedGateState.setOpenGateState(openGateState)
// inject ClosedGateState instance for not creating it inside of OpenGateState class
openGateState.setClosedGateState(closedGateState)
// starting with closed state
Gate gate = new Gate(closedGateState)
gate.payOK()
gate.enter()
//...
class OpenGateState implements GateState {
private GateState closedGateState;
public OpenGateState() {
}
public void setClosedGateState(GateState closedGateState) {
this.closedGateState = closedGateState
}
public GateState enter() {
return closedGateState;
}
public GateState payOK() {
return this;
}
public GateState payFail() {
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment