//State類是個(gè)狀態(tài)類
public class State {
private String value;
public void method1(){
System.out.println("execute the first opt!");
}
public void method2(){
System.out.println("execute the second opt!");
}
}
//Context類實(shí)現(xiàn)切換
public class Context {
private State state;
public Context(State state) {
this.state = state;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public void method() {
if (state.getValue().equals("state1")) {
state.method1();
} else if (state.getValue().equals("state2")) {
state.method2();
}
}
}
//測(cè)試
public class Test {
public static void main(String[] args) {
State state = new State();
Context context = new Context(state);
//設(shè)置第一種狀態(tài)
state.setValue("state1");
context.method();
//設(shè)置第二種狀態(tài)
state.setValue("state2");
context.method();
}
}