[java design pattern] state pattern

Step 1: Create a state class State

public class State {
     private String value;

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
     
	public void method1() {
		System.out.println("I am online");
	}
     
	public void method2() {
		System.out.println("I am offline");
	}
     
}

Step 2: Create a control state class Context

public class Context {
     //Introduce state instance
	 private State state;

	public Context(State state) {
		super();
		this.state = state;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}
	 
	public void method() {
		if(state.getValue().equals("up")) {
			state.method1();
		}else if(state.getValue().equals("down")) {
			state.method2();
		}
	}
}

Step 3: Test

public class Test {
   public static void main(String[] args) {
	 State state=new State();
	 Context context=new Context(state);
	 state.setValue("up");
	 context.method();
	 state.setValue("down");
	 context.method();
  }
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805415&siteId=291194637