Design Patterns Java - State Php

1) What have we got at the beginning?

We have an object "Context" which can has different states.

In our example: "one" and "two"

Methods "methodA" and "methodB" behave differently for each state, as we can see this in "Context",
In addition of this, they're changing states after calling


public class Context
{
    public static enum State
    {
        one, two
    }

    protected State state;

    public void methodA()
    {
        if (state == State.one)
        {
            System.out.println("MethodA doing something related with state one");
            state = State.two;
        }
        else
        {
            System.out.println("MethodA doing something related with state two");
            state = State.one;
        }
    }

    public void methodB()
    {
        if (state == State.one)
        {
            System.out.println("MethodB doing something related with state one");
            state = State.two;
        }
        else
        {
            System.out.println("MethodB doing something related with state two");
            state = State.one;
        }
    }

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

public class Client
{
    public static void main(String[] args)
    {
        Context context = new Context();
        context.setState(Context.State.one);

        context.methodA();
        context.methodB();
        context.methodB();
        context.methodA();
    }
}




2) What are cons?

Can be more states, we would have to add next conditionals in each method

3) What can we do?

We can use "State" pattern means we will created separate classes for every possible state of "Context" object.