Menu
CoddyTech

回顾:可选策略

Coddy 面向 C# 开发者的 PHP 课程的第 38 课,共 48 课。

challenge icon

挑战

简单

输入是 [amount,double]。Rule 定义了 evaluate(int):int。KeepRule 返回输入值;DoubleRule 将输入值乘以 2。Evaluator(Rule) 的 run(int):int 会委托给规则,并接受第三方规则。驱动程序根据布尔值进行选择。

提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明时不要打印内容;不要替换启动程序,也不要在模块中读取输入。输入符合指定的类型和范围。

编辑 Rule.php、KeepRule.php、DoubleRule.php、Evaluator.php。main.php 是锁定的入口文件。依赖项通过 require_once __DIR__ 和相对文件名引入。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Rule.php";
require_once __DIR__."/KeepRule.php";
require_once __DIR__."/DoubleRule.php";
require_once __DIR__."/Evaluator.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$r=new class implements Rule {public function evaluate(int $n):int{return $n+5;}};ensure((new Evaluator($r))->run(4)===9 && (new KeepRule())->evaluate(3)===3 && (new DoubleRule())->evaluate(3)===6,"all policies");
echo (string)(new Evaluator($input[1]?new DoubleRule():new KeepRule()))->run($input[0]),"\n";

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器