Design Patterns PHP - State Java

1) What have we done?

Firstly we created interface "State"


interface State
{
    public function methodA(Context $context);

    public function methodB(Context $context);
}




We just implemented concrete "States" = "StateOne" and "StateTwo" for possible "Context" states


class StateOne implements State
{
    /**
     * @param Context $context
     */
    public function methodA(Context $context)
    {
        echo 'methodA doing something related with the state one' . PHP_EOL;
        $context->setStateTwo();
    }

    /**
     * @param Context $context
     */
    public function methodB(Context $context)
    {
        echo 'methodB doing something related with the state one' . PHP_EOL;
        $context->setStateOne();
    }
}

class StateTwo implements State
{
    /**
     * @param Context $context
     */
    public function methodA(Context $context)
    {
        echo 'methodA doing something related with the state two' . PHP_EOL;
        $context->setStateTwo();
    }

    /**
     * @param Context $context
     */
    public function methodB(Context $context)
    {
        echo 'methodB doing something related with the state two' . PHP_EOL;
        $context->setStateOne();
    }
}




Now "Context" object executes proper methods from aggregated "StateOne" or "StateTwo"


class Context
{
    /**
     * @var StateOne
     */
    protected $stateOne;

    /**
     * @var StateTwo
     */
    protected $stateTwo;

    /**
     * @var State
     */
    protected $currentState;

    public function methodA()
    {
        $this->currentState->methodA($this);
    }

    public function methodB()
    {
        $this->currentState->methodB($this);
    }

    public function setStateOne()
    {
        if ($this->stateOne == null)
            $this->stateOne = new StateOne();
        $this->currentState = $this->stateOne;
    }

    public function setStateTwo()
    {
        if ($this->stateTwo == null)
            $this->stateTwo = new StateTwo();
        $this->currentState = $this->stateTwo;
    }
}




2) What has changed in Client ?

We set initial state and call executes methods in Client


$context = new Context();

$context->setStateOne();
$context->methodA();
$context->methodB();
$context->methodB();
$context->methodA();




This is whole conception of this pattern