简单工厂模式

普通初学者喜欢的写法

例子:实现一个简单计算器


class Program
{
    public $symbol;
    public $num1;
    public $num2;

    public function __construct($symbol, $num1, $num2)
    {
        $this->symbol = $symbol;
        $this->num1 = $num1;
        $this->num2 = $num2;
    }

    public function calculate()
    {
        switch ($this->symbol) {
            case '+':
                $result = $this->num1 + $this->num2;
                break;
            case '-':
                $result = $this->num1 - $this->num2;
                break;
            case '*':
                $result = $this->num1 * $this->num2;
                break;
            case '/':
                if ($this->num2 != 0) {
                    $result = $this->num1 / $this->num2;
                } else {
                    $result = "除数不能为0";
                }
                break;
            default:
                $result = "运算符错误";
        }

        return $result;
    }
}

$program = new Program('+', 1, 14);
$result = $program->calculate();
print_r($result);//15

在上面的代码中存在的缺点:
紧耦合,不易扩展,如果新增了一个平方根运算,却需要让加减乘除都来参与编译,如果一不小心把加法运算改成了减法,那就麻烦了。

使用简单工厂模式重新实现达到解耦的目的

将加减乘除解耦,每一个运算用单独的类去写,再用工厂模式实例化出合适的对象,通过多态返回计算器结果,后面如果再加一个平方根运算可以新增一个平方根的类,如果需要修改加法运算,那就只需要修改OperationAdd类。


class Operation
{
    public $num1;
    public $num2;
}

class OperationAdd extends Operation
{
    public function getResult()
    {
        $result = $this->num1 + $this->num2;
        return $result;
    }
}

class OperationSub extends Operation
{
    public function getResult()
    {
        $result = $this->num1 - $this->num2;
        return $result;
    }
}

class OperationMul extends Operation
{
    public function getResult()
    {
        $result = $this->num1 * $this->num2;
        return $result;
    }
}

class OperationDiv extends Operation
{
    public function getResult()
    {

        if ($this->num2 != 0) {
            $result = $this->num1 / $this->num2;
        } else {
            $result = "除数不能为0";
        }
        return $result;
    }
}

class OperationFactory
{
    public static function createOperate($symbol)
    {
        switch ($symbol) {//多态
            case '+':
                $result = new OperationAdd();
                break;
            case '-':
                $result = new OperationSub();
                break;
            case '*':
                $result = new OperationMul();
                break;
            case '/':
                $result = new OperationDiv();
                break;
            default:
                $result = NULL;
        }
        return $result;
    }
}

$operationFactory = OperationFactory::createOperate('+');
$operationFactory->num1 = 21;
$operationFactory->num2 = 11;

echo $operationFactory->getResult();//32
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!