php简单工厂模式

工厂类中有一个创建对象的方法,根据传入参数的不同来生成不同的对象
class Operation extends Model
{ private $numberA;
private $numberB; public function getResult(){ $result = 0; return $result; } public function getNumberA(){ return $this->numberA;
}
public function setNumberA($numberA){ $this->numberA = $numberA; } public function getNumberB(){ return $this->numberB;
}
public function setNumberB($numberB){ $this->numberB = $numberB; } }
class OperationAdd extends  Operation
{ public function getResult()
{
$result = 0 ; $result = $this->numberA + $this->numberB; return $result; } }
class OperationSub extends  Operation
{ public function getResult()
{
$result = 0; $result = $this->numberA - $this->numberB; return $result;
} }
class OperationMul extends  Operation
{
public function getResult(){ $result = 0; $result = $this->numberA * $this->numberB; return $result; } }
class OperationDiv extends  Operation
{
public  function  getResult(){

    $result =  0;
if ($this->numberA == 0){ throw new HttpException("除数不能为0");
} $result = $this->numberA / $this->numberB; return $result;
}
}

class Factory extends Model
{ private $type; public function __construct($type,array $config = [])
{
$this->type = $type;
parent::__construct($config);
} public function createOperate(){
switch ($this->type){
case "+": return new OperationAdd(); break; case "-": return new OperationSub(); break; case "*": return new OperationMul();
break; case "/": return new OperationDiv();
break; }
     }

}

$factory  = new Factory("+");

$operation = $factory->createOperate();

$operation->numberA = 2;

$operation->numberB = 1;

$result = $operation->getResult();

echo $result;
上一篇:上传下载---图片|文件


下一篇:nsenter工具进入docker