简单工厂模式是由一个工厂对象决定创建出哪一种类的实例。
比如现在我们用面向对象的方式封装了一个运算类 Operation
<?php
/**
* Created by phpStorm.
* User: binwei
* Date: 2019/5/18
* Time: 17:02
*/
class Operation
{
public static function getResult($num1, $num2, $operate)
{
$result = 0;
switch ($operate) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = $num1 / $num2;
break;
}
return $result;
}
}
现在要解耦,将加减乘除运算分离,以至增加和修改都不影响其他代码,我们可以将 Operation
类分成加减乘除四个类,相互不影响,比如加法类
<?php
/**
* Created by phpStorm.
* User: binwei
* Date: 2019/5/18
* Time: 17:14
*/
class OperationAdd
{
public function getResult($num1, $num2)
{
return $num1 + $num2;
}
}
那么什么是工厂模式呢?现在我们需要一个工厂类来通过操作符直接返回对应的实例,比如是加法操作符,那么工厂类就给我返回 OperationAdd
的实例。
<?php
/**
* Created by phpStorm.
* User: binwei
* Date: 2019/5/18
* Time: 17:31
*/
require_once "OperationAdd.php";
require_once "OperationSub.php";
require_once "OperationMul.php";
require_once "OperationDiv.php";
class OperationFactory
{
public static function createOperate($operate)
{
$oper = null;
switch ($operate) {
case '+':
$oper = new OperationAdd();
break;
case '-':
$oper = new OperationSub();
break;
case '*':
$oper = new OperationMul();
break;
case '/':
$oper = new OperationDiv();
break;
}
return $oper;
}
}
现在比如我们有 2 个数要进行加法运算,那么就可以这么做了:
<?php
/**
* Created by phpStorm.
* User: binwei
* Date: 2019/5/18
* Time: 17:35
*/
require_once "OperationFactory.php";
$num1 = 1;
$num2 = 12;
$op = OperationFactory::createOperate("+");
$rs = $op->getResult($num1, $num2);
echo $rs;
比如后期我们要进行其他复杂的运算,比如立方根等,我们只需要增加对应的运算类,再在工厂类中增加对应的分支就好了。
这就是一个简单工厂模式的一个简单使用。