
...
<?php /* The state pattern encapsulates the varying behavior for the same object based on its internal state, making an object appear as if it has changed its class. */ interface Statelike { public function writeName(StateContext $context, $name); } class StateLowerCase implements Statelike { public function writeName(StateContext $context, $name) { echo strtolower($name); $context->setState(new StateMultileUpperCase()); } } class StateMultileUpperCase implements Statelike { private $count = 0; public function writeName(StateContext $context, $name) { $this->count++; echo strtoupper($name); if ($this->count > 1) { $context->setState(new StateLowerCase()); } } } class StateContext { private $state; public function setState(Statelike $state) { $this->state = $state; } public function writeName($name) { $this->state->writeName($this, $name); } } $stateContext = new StateContext(); $stateContext->setState(new StateLowerCase()); $stateContext->writeName('Monday<br/>'); $stateContext->writeName('TuesDay<br/>'); $stateContext->writeName('Wednesday<br/>'); $stateContext->writeName('Thursday<br/>'); $stateContext->writeName('Friday<br/>'); $stateContext->writeName('Saturday<br/>'); $stateContext->writeName('Sunday<br/>'); ?>