Created
September 11, 2013 07:53
-
-
Save darraghenright/6520512 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface TurnstileInterface | |
{ | |
public function insertCoin(); | |
public function pass(); | |
} | |
class Turnstile implements TurnstileInterface | |
{ | |
private $state; | |
private $opened; | |
private $closed; | |
function __construct() | |
{ | |
$this->opened = new TurnstileStateOpened(); | |
$this->closed = new TurnstileStateClosed(); | |
$this->state = $this->closed; | |
} | |
public function insertCoin() | |
{ | |
$this->state->insertCoin(); | |
$this->state = $this->opened; | |
} | |
public function pass() | |
{ | |
$this->state->pass(); | |
$this->state = $this->closed; | |
} | |
} | |
class TurnstileStateOpened implements TurnstileInterface | |
{ | |
public function insertCoin() | |
{ | |
throw new Exception('Coin already inserted!' . PHP_EOL); | |
} | |
public function pass() | |
{ | |
echo 'pass! the gate is open!' . PHP_EOL; | |
} | |
} | |
class TurnstileStateClosed implements TurnstileInterface | |
{ | |
public function insertCoin() | |
{ | |
echo 'thanks! opening the gate!' . PHP_EOL; | |
} | |
public function pass() | |
{ | |
throw new Exception('Alarm! Security!' . PHP_EOL); | |
} | |
} | |
$turnstile = new Turnstile(); | |
$turnstile->insertCoin(); | |
$turnstile->pass(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment