State_Pattern

package state_pattern;

public abstract class State {
    public abstract void Handle(Context context);
}

package state_pattern;

public class ConcreteStateA extends State{
    @Override
    public void Handle(Context context) {//It implements the logic between related state.
        context.setState(new ConcreteStateB());//The current state decide the next state.
    }
}

package state_pattern;

public class ConcreteStateB extends State{
    @Override
    public void Handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}

package state_pattern;

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;
        System.out.println("The current state is " + this.state.getClass().getName());
    }
    public void request() {
        state.Handle(this);//The current class object as the parameter communicate
        //with state.The dynamic binding instead of "switch-case".
    }
}

package state_pattern;

public class Main {
    public static void main(String args[]) {
        Context c =  new Context(new ConcreteStateA());       
        c.request();
        c.request();
        c.request();
        c.request();
    }
}
/*
 * The current object's behavior is related to its state during the runtime.
 */

This is a general introduction to the 23 design patterns:
https://blog.csdn.net/GZHarryAnonymous/article/details/81567214

猜你喜欢

转载自blog.csdn.net/GZHarryAnonymous/article/details/82829778