<?php
interface Handler
{
public function handle($request);
}
abstract class AbstractHandler implements Handler
{
protected $successor;
public function setSuccessor(Handler $successor)
{
$this->successor = $successor;
}
public function handle($request)
{
if ($this->process($request) && $this->successor) {
$this->successor->handle($request);
}
}
abstract protected function process($request);
}
class AgeHandler extends AbstractHandler
{
protected function process($request)
{
if ($request['age'] < 18) {
echo "年齡必須大於等於18歲。";
return false;
}
return true;
}
}
class HeightHandler extends AbstractHandler
{
protected function process($request)
{
if ($request['height'] < 170) {
echo "身高必須大於等於170cm。";
return false;
}
return true;
}
}
class WeightHandler extends AbstractHandler
{
protected function process($request)
{
if ($request['weight'] < 60 || $request['weight'] > 80) {
echo "體重必須在60kg~80kg之間。";
return false;
}
return true;
}
}
class SkillHandler extends AbstractHandler
{
protected function process($request)
{
if ($request['running'] > 10 || $request['swimming'] > 120 || $request['biking'] > 15) {
echo "必須有一定的運動能力,包括50米短跑必須在10秒以內、100米游泳必須在2分鐘以內、50米腳踏車騎行必須在15秒以內。";
return false;
}
return true;
}
}
$ageHandler = new AgeHandler();
$heightHandler = new HeightHandler();
$weightHandler = new WeightHandler();
$skillHandler = new SkillHandler();
$ageHandler->setSuccessor($heightHandler);
$heightHandler->setSuccessor($weightHandler);
$weightHandler->setSuccessor($skillHandler);
$request = [
'age' => 18,
'height' => 170,
'weight' => 90,
'running' => 11,
'swimming' => 110,
'biking' => 14
];
$ageHandler->handle($request);
本作品採用《CC 協議》,轉載必須註明作者和本文連結
我從未見過一個早起、勤奮、謹慎,誠實的人抱怨命運。