Last active
December 2, 2016 05:19
-
-
Save MilesChou/c7980023d2a1e2d381b8acfdb7d31e72 to your computer and use it in GitHub Desktop.
greeting
This file contains hidden or 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 | |
class Client | |
{ | |
public $greetingRules = []; | |
public function __construct() | |
{ | |
$this->greetingRules[] = new MorningGreeting(); | |
$this->greetingRules[] = new AfternoonGreeting(); | |
$this->greetingRules[] = new EveningGreeting(); | |
} | |
/** | |
* @param int $hour | |
*/ | |
public function getGreeting($hour) | |
{ | |
/** | |
* @var $greetingRule GreetingRule | |
*/ | |
foreach ($this->greetingRules as $greetingRule) { | |
if ($greetingRule->isRight($hour)) { | |
return $greetingRule->getGreeting(); | |
} | |
} | |
throw new Exception("Error when greeting!"); | |
} | |
} | |
class MorningGreeting implements GreetingRule | |
{ | |
public function getGreeting() | |
{ | |
return "Good Morning"; | |
} | |
public function isRight($hour) | |
{ | |
if ($hour >= 6 && $hour < 12) { | |
return true; | |
} | |
return false; | |
} | |
} | |
class AfternoonGreeting implements GreetingRule | |
{ | |
public function getGreeting() | |
{ | |
return "Good Afternoon"; | |
} | |
public function isRight($hour) | |
{ | |
if ($hour >= 12 && $hour < 18) { | |
return true; | |
} | |
return false; | |
} | |
} | |
class EveningGreeting implements GreetingRule | |
{ | |
public function getGreeting() | |
{ | |
return "Good Evening"; | |
} | |
public function isRight($hour) | |
{ | |
if ($hour >= 18 && $hour < 22) { | |
return true; | |
} | |
return false; | |
} | |
} | |
interface GreetingRule | |
{ | |
/** | |
* @param int $hour | |
* @return bool | |
*/ | |
public function isRight($hour); | |
/** | |
* @return string | |
*/ | |
public function getGreeting(); | |
} | |
$client = new Client(); | |
echo $client->getGreeting(7) . PHP_EOL; | |
echo $client->getGreeting(13) . PHP_EOL; | |
echo $client->getGreeting(19) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment