Design Patterns PHP - State Java

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


class Context
{
    /**
     * @var string $state
     */
    protected $state;

    public function methodA()
    {
        if ($this->state == 'one') {
            echo 'methodA doing something related with the state one' . PHP_EOL;
            $this->state = 'two';
        } elseif ($this->state == 'two') {
            echo 'methodA doing something related with the state two' . PHP_EOL;
            $this->state = 'one';
        }
    }

    public function methodB()
    {
        if ($this->state == 'one') {
            echo 'methodB doing something related with the state one' . PHP_EOL;
            $this->state = 'two';
        } elseif ($this->state == 'two') {
            echo 'methodB doing something related with the state two' . PHP_EOL;
            $this->state = 'one';
        }
    }

    /**
     * @param string $state
     * @return State
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }
}

$context = new Context();
$context->setState('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.