lundi 20 novembre 2017

Android Model-View-Presenter with State Machine design pattern

Let's say I have an element with 3 states: state1, state2, state3. The most basic flow is:

state1 -> state2 -> state3 -> state1 -> ... etc.

The states are changed on button click. I implemented the State Machine design pattern to manage those states.

Of course, when the state changes, certain things change in the layout and in the logical layer. The problem is, I want to know how would an MVP implementation look like with those state changes. Where should I put the view-changing logic, and where should I put the model-changing logic. A basic example would be great.

Here is my code:

MainActivity.java:

StateContext stateContext;

@OnClick(R.id.button_change_state)
public void onClickChangeStateButton(View view) {
    stateContext.takeAction();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    stateContext = new StateContext();
}

StateContext.java:

public class StateContext {
    private State state;
    public StateContext() {
        this.state = new State1();
    }

    public void setState(final State state) {
        this.state = state;
    }

    public void takeAction() {
        state.takeAction(this);
    }

}

State.java:

public interface State {
    void takeAction(StateContext stateContext);
}

example State1.java:

public class State1 implements State {

    @Override
    public void takeAction(StateContext stateContext) {
        Toast.makeText(Application.getContext(), "Graphical actions here, going to state2", Toast.LENGTH_SHORT ).show();
        stateContext.setState(new State2());
    }
}

Aucun commentaire:

Enregistrer un commentaire