interface State // Interface an welches sich die Konkreten Objekte halten muessen { public function nextState ( Context $_context ); } class On implements State // Konkretes Objekt 1 { public function nextState ( Context $_context ) { $_context->setState(new Off()); return 'turn Off ['.__METHOD__.']'; } } class Off implements State // Konkretes Objekt 2 { public function nextState ( Context $_context ) { $_context->setState(new On()); return 'turn On ['.__METHOD__.']'; } }
class Context // Context zur Speicherung des aktuellen State's { private $state = NULL; function __construct ( State $_state ) { $this->setState($_state); } /** * Methode zum setzen eines neuen Status * @param State $_state : Uebergabe des neuen Konkreten Objekts */ public function setState ( State $_state ) { $this->state = $_state; } /** * Weiterschalten zum naechsten State */ public function nextState ( ) { return $this->state->nextState($this).'<br />'; } }
// Test $cContext = new Context(new Off()); echo $cContext->nextState(); echo $cContext->nextState(); echo $cContext->nextState(); echo $cContext->nextState(); echo $cContext->nextState();
/**
Ausgabe
turn On [Off::nextState]
turn Off [On::nextState]
turn On [Off::nextState]
turn Off [On::nextState]
turn On [Off::nextState]
*/