标签:
我的认为:所为工厂模式是事先有一系类class,一个工厂类‘
工厂类根据不同的参数创建不同的对象,调用各自的方法;
php利用工厂模式实现计算器:
?php /** * Created by PhpStorm. * User: modern * Date: 16-7-19 * Time: 下午5:24 * 简单工厂模式两数运算器 */ echo "hello factory models<br/>"; echo "begin<br/>"; if(isset($_GET[‘param1‘])){ $param1 = $_GET[‘param1‘]; }else{ $param1 = 0; } if(isset($_GET[‘param2‘])){ $param2 = $_GET[‘param2‘]; }else{ $param2 = 0; } if(isset($_GET[‘param3‘])){ $param3 = $_GET[‘param3‘]; }else{ $param3 = ‘‘; } interface Init { public function getResult($a,$b); } class OperateAdd implements Init { public function getResult($a,$b) { return $a + $b; } } class OperateSub implements Init { public function getResult($a,$b) { return $a - $b; } } class OperateMul implements Init { public function getResult($a,$b) { return $a * $b; } } class OperateDiv implements Init { public function getResult($a,$b) { try{ if($b == 0){ throw new Exception("除数不能为0"); }else{ return $a / $b; } }catch (\Exception $e){ echo "运算发生错误:".$e->getMessage(); } } } class Calc { public static function operate($operate) { try{ switch($operate) { case ‘+‘: return new OperateAdd();break; case ‘-‘: return new OperateSub();break; case ‘*‘: return new OperateMul();break; case ‘/‘: return new OperateDiv();break; default: throw new Exception("标识错误!"); } }catch (\Exception $e){ echo ‘运算错误:‘.$e->getMessage(); } } } $me = Calc::operate($param3); if(gettype($me) == ‘object‘){ $result = $me->getResult($param1,$param2); echo $result; }
解说:本例中,定义接口类init,再定义加减乘除四个类分别实现这个接口类,这样每个运算方法都须事先方法getResult(),定义工厂类,工厂类里定义一个静态方法,用户根据不同参数创建各个方法对象.最后再调用getResult()实现运算.
标签:
原文地址:http://www.cnblogs.com/sign-ptk/p/5685915.html