php--class的工厂模式的示例
发布日期:2021-05-06 21:10:07 浏览次数:4 分类:技术文章

本文共 2090 字,大约阅读时间需要 6 分钟。

getMessage(); } }}//类的实例化$test = new calc();echo '+ ='.$test->calculate(100,99,'+');echo "
";echo '- ='.$test->calculate(100,99,'-');echo "
";echo '* ='.$test->calculate(100,99,'*');echo "
";echo '/ ='.$test->calculate(100,99,'/');echo "
";echo '/ ='.$test->calculate(100,0,'/');echo "
";echo '% ='.$test->calculate(100,99,'%');echo "
";

工厂模式:

echo "

";//接口interface calc1{ public function getValue($num1,$num2);}//加法,继承接口并实现class math_add implements calc1{ public function getValue($num1, $num2) { return $num1 + $num2; }}//减法class math_sub implements calc1{ public function getValue($num1, $num2) { return $num1 - $num2; }}//乘法class math_mul implements calc1{ public function getValue($num1, $num2) { return $num1 * $num2; }}//除法class math_div implements calc1{ public function getValue($num1, $num2) { try { if($num2 == 0) { throw new Exception('chu shu bu meng wei 0'); } else { return $num1 / $num2; } } catch (Exception $e) { echo "wrong :".$e->getMessage(); } }}//工厂类,静态方法创建对象class factory1{ public static function createObject($operator) { switch ($operator) { case '+': return new math_add(); break; case '-': return new math_sub(); break; case '*': return new math_mul(); break; case '/': return new math_div(); break; } }}//创建加法类实例$fac1 = factory1::createObject('+');echo '+ ='.$fac1->getValue(100,99);echo "
";//创建减法类实例$fac2 = factory1::createObject('-');echo '- ='.$fac2->getValue(100,99);echo "
";//创建乘法类实例$fac3 = factory1::createObject('*');echo '* ='.$fac3->getValue(100,99);echo "
";//创建除法类实例$fac4 = factory1::createObject('/');echo '/ ='.$fac4->getValue(100,99);echo "
";//除数为0$fac5 = factory1::createObject('/');echo '+ ='.$fac5->getValue(100,0);echo "
";

 

上一篇:php--class的单例模式
下一篇:php--json_decode

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月30日 17时30分48秒