concept

The same structure as the policy pattern, but different in purpose and nature. The behavior of state patterns is parallel and not replaceable; The behavior of the policy pattern is independent and interchangeable. The state pattern wraps the behavior of an object in different state objects so that the behavior of the object changes as its internal state changes. The benefits are also extensibility and clarity; The disadvantage is also increasing the number of classes and objects.

Usage scenarios

  • The behavior of an object depends on its state
  • The code contains a large number of conditional statements related to object state (removing excessive if-else by polymorphism)

implementation

interface State{ void fun(); } public class State1 implements State{// Implements State after being started public voidfun() {/ /do something;
        System.out.println("hello"); }} public class State2 implements State{// State2 implements State none public voidfun() {/ /do nothing;
        return;
    }
}

public interface TVController{
    void poweron();
    void poweroff();
}

public class TVContext implements TVController{
    State mState;

    public TVContext(){ mState = new State2(); // Initialize to shutdown state} private voidsetState(State s){
        mState = s;
    }

    @Override
    public void poweron() {/ / bootsetState(new State1()); } @override public void poweroff{// poweroffsetState(new State2());
    }

    public void watchMstate.fun (){// Watch TV (only when it is on, nothing is on when it is off); } } public class Test { public static void main(String[] args){ TVContext tv = new TVContext(); tv.poweron(); tv.watch(); tv.poweroff(); tv.watch(); }}Copy the code