封装加减乘除类
要求:能够遵守开闭原则进行扩展以及单一职责原则,每个类目对外的方法属性越少越好
<?php
interface SuanShuInterFace
{
public function calc($a,$b);
}
// 加法类
class Add implements SuanShuInterFace
{
public function calc($a,$b){
return $a + $b;
}
}
//减法类
class Reduce implements SuanShuInterFace
{
public function calc($a,$b){
return $a - $b;
}
}
//乘法类
class Ride implements SuanshuInterFace
{
public function calc($a,$b){
return $a * $b;
}
}
//除法类
class Except implements SuanShuInterFace
{
public function calc($a,$b){
if($b === 0){
echo '被除数不能为 0 ';die;
}
return $a / $b;
}
}
class Call
{
public function __construct(SuanShuInterFace $shu,$a,$b){
echo '计算结果为:'.$shu->calc($a,$b).'<br>';
}
}
$a = 10;
$b = 2;
new Call(new Add(),$a,$b);
new Call(new Reduce(),$a,$b);
new Call(new Ride(),$a,$b);
new Call(new Except(),$a,$b);
|