Skip to content

Instantly share code, notes, and snippets.

@gustavofonseca
Created May 30, 2011 18:40
Show Gist options
  • Save gustavofonseca/999288 to your computer and use it in GitHub Desktop.
Save gustavofonseca/999288 to your computer and use it in GitHub Desktop.
State example in java(GoF design pattern) (not responsible for this code)
package br.padroes.gof.comportamental.state;
public class AcceptedState implements State {
public void grantPermission(StateContext ctx) {
}
public void requestPermission(StateContext ctx){
System.out.println("Requesting permission");
ctx.setState(ctx.getRequestedState());
}
public String getStatus() {
return "Request Received";
}
}
package br.padroes.gof.comportamental.state;
public class ClienteState {
public static void main(String[]args) {
StateContext ctx = new StateContext();
ctx.acceptApplication();
ctx.requestPermission();
ctx.grantPermission();
System.out.println(ctx.getStatus());
}
}
package br.padroes.gof.comportamental.state;
public class GrantedState implements State {
public void grantPermission(StateContext ctx) {
System.out.println("Invalid state");
}
public void requestPermission(StateContext ctx){
System.out.println("Invalid state");
}
public String getStatus() {
return "Granted";
}
}
package br.padroes.gof.comportamental.state;
public class RequestedState implements State {
public void grantPermission(StateContext ctx) {
System.out.println("Granting Permission");
ctx.setState(ctx.getGrantedState());
}
public void requestPermission(StateContext ctx){
System.out.println("Permission already requested");
}
public String getStatus() {
return "Requested permission";
}
}
package br.padroes.gof.comportamental.state;
public interface State {
public void grantPermission(StateContext ctx);
public void requestPermission(StateContext ctx);
public String getStatus();
}
package br.padroes.gof.comportamental.state;
public class StateContext {
private State acceptedState;
private State requestedState;
private State grantedState;
private State state;
public StateContext() {
acceptedState = new AcceptedState();
requestedState = new RequestedState();
grantedState = new GrantedState();
state = null;
}
public void acceptApplication() {
this.state = acceptedState;
}
public void requestPermission() {
state.requestPermission(this);
}
public void grantPermission() {
state.grantPermission(this);
}
public String getStatus() {
return state.getStatus();
}
public void setState(State state) {
this.state = state;
}
public State getAcceptedState() {
return acceptedState;
}
public State getGrantedState() {
return grantedState;
}
public State getRequestedState() {
return requestedState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment