public interface Operation{
/*
* 获取结果
*/
public function get();
}
/*
* 加法类
*/
class OperationAdd implements Operation{
private $_NumA;
private $_NumB;
public function __construct($num1,$num2) {
$this->_NumA = $num1;
$this->_NumB = $num2;
}
public function get() {
return ($this->_NumA + $this->_NumB);
}
}
class OperationSub implments Operation {
private $_NumA;
private $_NumB;
public function __construct($num1,$num2) {
$this->_NumA = $num1;
$this->_NumB = $num2;
}
public function get() {
return ($this->_NumA - $this->_NumB);
}
}
public class OperaFactory{
private $_results;
private $_opera;
public function __construct() {
$this->_results = 0;
}
public function Calculate($num1,$num2,$operator) {
swtich($operator) {
case '+':
$this->_opera = new OperationAdd($num1,$num2);
break;
case '-':
$this->_opera = new OperationSub($num1,$num2);
break;
default:
break;
}
$this->_results = $this->_opera->get();
return $this->_results;
}
}
简单工厂模式定义
简单工厂的 UML 图
简单工厂模式中的各个角色以及相应职责:
具体实例
优缺点
在讲述优缺点的之前,我们可以先思考一个问题,就当前的例子而言,如果我们需要添加一个 乘法的类,我们只需要定义一个类方法继承Operation这个接口,然后实现该方法,最后在OperaFactory中的Calculate中加一个新的分支
优点:
从上述例子以及简单的思考,不难看出通过简单工厂设计模式使得程序变得更加灵活,便于修改,并易于复用,降低了代码的耦合性
缺点:
如我们在代码所见那样,所有的创建逻辑都在OperaFactory中的Calculate,一旦其不能正常工作,整个系统都将收到影响