状态接口类
状态0实现类
状态1实现类
状态工厂类:
最后,编写客户端测试类
运行结果:
当前状态为状态1
该模式,只要传递一个静态的状态,就可以执行该需要状态的执行类。
package com.fczfr.pattern.behavior.state.sample1;
public interface State {
// 状态0
public final static int STATUS_0 = 0;
// 状态1
public final static int STATUS_1 = 1;
public void sampleOperation();
public int getStatus();
}
状态0实现类
package com.fczfr.pattern.behavior.state.sample1;
public class State0 implements State {
public void sampleOperation() {
System.out.println("当前状态为状态0");
}
public int getStatus() {
return this.STATUS_0;
}
}
状态1实现类
package com.fczfr.pattern.behavior.state.sample1;
public class State1 implements State {
public void sampleOperation() {
System.out.println("当前状态为状态1");
}
public int getStatus() {
return this.STATUS_1;
}
}
状态工厂类:
package com.fczfr.pattern.behavior.state.sample1;
import java.util.ArrayList;
import java.util.List;
public class StateFactory {
List<State> stateList = null;
public StateFactory(){
stateList = new ArrayList<State>();
stateList.add(new State0());
stateList.add(new State1());
}
public State getState(int status){
for(State state:stateList){
if(state.getStatus()==status){
return state;
}
}
return null;
}
}
最后,编写客户端测试类
package com.fczfr.pattern.behavior.state.sample1;
public class Client {
public static void main(String[] args) {
StateFactory factory = new StateFactory();
factory.getState(State.STATUS_1).sampleOperation();
}
}
运行结果:
当前状态为状态1
该模式,只要传递一个静态的状态,就可以执行该需要状态的执行类。