最近在看《大话设计模式》,打算写个系列笔记,在帮助到新手的同时可以巩固自己的知识,希望能坚持下去吧。
工厂模式的核心是创建一个工厂类,通过这个类创建所需要的对象,这样做的好处是增加了代码的可拓展性,降低了耦合度,容易修改,并且易于复用。
<?php
interface Operation{
public function getRes($numA,$numB);
}
# 加法类
class OperationAdd implements Operation{
public function getRes($numA,$numB){
return $numA + $numB;
}
}
# 减法类
class OperationSub implements Operation{
public function getRes($numA,$numB){
return $numA - $numB;
}
}
# 乘法类
class OperationMul implements Operation{
public function getRes($numA,$numB){
return $numA * $numB;
}
}
# 除法类
class OperationDiv implements Operation{
public function getRes($numA,$numB){
try {
if ($numB == 0) {
throw new Exception("除数不能为0", 1);
}else{
return $numA / $numB;
}
} catch (Exception $e) {
echo "错误信息:".$e->getMessage();
}
}
}
class OperationFactory{
public static function createOperate($operate){
switch ($operate) {
case '+':
$oper = new OperationAdd();
break;
case '-':
$oper = new OperationSub();
break;
case '*':
$oper = new OperationMul();
break;
case '/':
$oper = new OperationDiv();
break;
}
return $oper;
}
}
class Client{
public function main(){
$oper = OperationFactory::createOperate('+');
$res = $oper->getRes(1,2);
echo $res;
}
}
$client = new Client();
$client->main();