标签:单例模式
<?php
//定义接口
interface Calc{
public function getValue($num1,$num2);
}
//创建实现接口的实体类
class Add implements Calc{
public function getValue($num1,$num2) {
return $num1 + $num2;
}
}
class Sub implements Calc{
public function getValue($num1,$num2) {
return $num1 - $num2;
}
}
class Mul implements Calc{
public function getValue($num1,$num2) {
return $num1 * $num2;
}
}
class Div implements Calc{
public function getValue($num1,$num2) {
try {
if($num2 == 0) {
throw new Exception(‘除数不能为0‘);
} else {
return $num1/$num2;
}
} catch (Exception $e) {
echo "错误信息:" . $e->getMessage();
}
}
}
//创建一个工厂,生成基于给定信息的实体类的对象
class Factory{
public static function createObj($operate) {
switch ($operate) {
case ‘+‘:
return new Add();
break;
case ‘-‘:
return new Sub();
break;
case ‘*‘:
return new Mul();
break;
case ‘/‘:
return new Div();
break;
}
}
}
$test = Factory::createObj(‘-‘);
echo $test->getValue(1,4);
?>
标签:单例模式
原文地址:http://chenxiaolong.blog.51cto.com/8786841/1790707