Java教程

状态模式

本文主要是介绍状态模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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());
            }
        }
    }
}

 

这篇关于状态模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!