设计模式PHP版二 - 工厂模式

版权声明:转载需附上本文地址 https://blog.csdn.net/weikaixxxxxx/article/details/88832706
<?php

// 定义一个接口
interface Factory
{
    public function operation($option);
}
// 运算工厂
class OperationFactory implements Factory
{
    // 实现接口
    public function operation($option)
    {
        // 输入什么符号就返回什么对象实例
        switch ($option) {
            case '+':
                return new Addition();
            case '-':
                return new Subtraction();
            case '*':
                return new Multiplication();
            case '/':
                return new Division();
        }
    }
}

/**
 * 运算类
 *
 *
 * Class Operation
 */
class Operation
{
    /**
     * @var int 值A
     */
    protected $numA = 0;
    /**
     * @var int 值B
     */
    protected $numB = 0;

    /**
     * 设置值A
     *
     * @param int $num 数字
     * @return int
     */
    public function setNumA($num){
        $this->numA = $num;
    }

    /**
     * 设置值B
     *
     * @param int $num 数字
     * @return int
     */
    public function setNumB($num){
        $this->numB = $num;
    }

    /**
     * 返回结果
     *
     * @return int
     */
    protected function getResult(){}
}
// 加法类
class Addition extends Operation
{
    public function getResult()
    {
        $result = $this->numA + $this->numB;
        return $result;
    }
}
// 减法类
class Subtraction extends Operation
{
    public function getResult()
    {
        $result = $this->numA - $this->numB;
        return $result;
    }
}
// 乘法类
class Multiplication extends Operation
{
    public function getResult()
    {
        $result = $this->numA * $this->numB;
        return $result;
    }
}
// 除法类
class Division extends Operation
{
    public function getResult()
    {
        $result = $this->numA / $this->numB;
        return $result;
    }
}

// 实例化运算工厂
$object = new OperationFactory();
// 选项为加法
$obj = $object->operation('+');
// 赋值,此时$obj为Addition类,因它继承了Operation类,所以可以给Operation类传值
$obj->setNumA(1);
$obj->setNumB(1);
var_dump($obj->getResult()); // 输出2

$obj = $object->operation('-');
$obj->setNumA(2);
$obj->setNumB(1);
var_dump($obj->getResult());

$obj = $object->operation('*');
$obj->setNumA(2);
$obj->setNumB(2);
var_dump($obj->getResult());

$obj = $object->operation('/');
$obj->setNumA(4);
$obj->setNumB(2);
var_dump($obj->getResult());

看起来很麻烦的样子,其实有个好处,你只需更改运算符和需要参与运算的数字就行了,调用的写法是一样的。
例:

$object = new OperationFactory();
$obj = $object->operation('/');
$obj->setNumA(4);
$obj->setNumB(2);
var_dump($obj->getResult());

如果用平时new的形式,你得这样子

// 加法类
class Add
{
    public function getResult($numA, $numB)
    {
        $result = $numA + $numB;
        return $result;
    }
}

$add = new Add();
var_dump($add->getResult(1, 1));

// 减法类
class Sub
{
    public function getResult($numA, $numB)
    {
        $result = $numA - $numB;
        return $result;
    }
}
$sub = new Sub();
var_dump($sub->getResult(2, 1));

猜你喜欢

转载自blog.csdn.net/weikaixxxxxx/article/details/88832706