【java设计模式】状态模式

步骤一:建立状态类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("我是在线状态");
	}
     
	public void method2() {
		System.out.println("我是离线状态");
	}
     
}

步骤二:建立控制状态类 Context

public class Context {
     //引入状态实例
	 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();
		}
	}
}

步骤三:测试

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();
  }
}



猜你喜欢

转载自blog.csdn.net/sinat_35821285/article/details/80109329