public class StatePattern { public static void main(String[] args) { Context context=new Context(); for (int i = 0; i < 10; i++) { context.handle(); } } }
public class Context { public boolean isPrveReadPGRead() { return prveReadPGRead; } public void setPrveReadPGRead(boolean prveReadPGRead) { this.prveReadPGRead = prveReadPGRead; } private boolean prveReadPGRead; private State state; //定义环境类的初始状态 public Context() { this.state = new ReadPGState(); } //设置新状态 public void setState(State state) { this.state = state; } //读取状态 public State getState() { return (state); } //对请求做处理 public void handle() { state.handle(this); } }
public abstract class State { public abstract void handle(Context context); }
public class ReadPGState extends State { @Override public void handle(Context context) { //读取pg数据 System.out.println("都PG数据"); System.out.println("发送mq"); context.setPrveReadPGRead(true); context.setState(new ReadQueueState()); } }
public class ReadQueueState extends State { @Override public void handle(Context context) { //上一次执行是否为pg if (context.isPrveReadPGRead()){ //map中是否包含Lsn boolean flag=true; if (flag){ //压入 System.out.println("map读取"); context.setPrveReadPGRead(false); flag=false; }else { context.setState(new ReadPGState()); } }else { boolean flag=true; //队列未满 if (flag){ //全部取出执行 System.out.println("连续map读取"); context.setPrveReadPGRead(false); flag=false; }else { context.setState(new ReadPGState()); } } } }