美文网首页
设计模式-简单工厂理解

设计模式-简单工厂理解

作者: winter_coder | 来源:发表于2020-02-28 08:52 被阅读0次

    这种模式在我理解,就是通过一个类似路由器的入口,创建属性相同但是操作不同的对象。

    最简单的结构:

    1. 一个基础类:可以是普通类,或者抽象类
    2. 不同的操作或行为类:继承上诉基础类
    3. 路由器类:可创建上诉行为类的对象

    举个栗子:

    <?php 
    /**
     * Operation 
     */
    class Operation
    {
        protected  $a = 0;
        protected  $b = 0;
        public function setA($a)
        {
            $this->a = $a;
        }
        public function setB($b)
        {
            $this->b = $b;
        }
        public function getResult()
        {
            $result = 0;
            return $result;
        }
    }
    /**
     * Add 
     */
    class OperationAdd extends Operation
    {
        public function getResult()
        {
            return $this->a + $this->b;
        }
    }
    /**
     * Mul
     */
    class OperationMul extends Operation
    {
        public function getResult()
        {
            return $this->a * $this->b;
        } 
    }
    /**
     * Sub
     */
    class OperationSub extends Operation
    {
        public function getResult()
        {
            return $this->a - $this->b;
        }
    }
    /**
     * Div
     */
    class OperationDiv extends Operation
    {
        public function getResult()
        {
            return $this->a / $this->b;
        }
    }
    /**
     * Operation Factory
     */
    class OperationFactory
    {
        public static function createOperation($operation)
        {
            switch ($operation) {
                case '+':
                    $oper = new OperationAdd();
                    break;
                case '-':
                    $oper = new OperationSub();
                    break;
                case '/':
                    $oper = new OperationDiv();
                    break;
                case '*':
                    $oper = new OperationMul();
                    break;
            }
            return $oper;
        }
    }
    // 客户端代码
    $operation = OperationFactory::createOperation('+');
    $operation->setA(1);
    $operation->setB(2);
    echo $operation->getResult() . PHP_EOL;
    

    相关文章

      网友评论

          本文标题:设计模式-简单工厂理解

          本文链接:https://www.haomeiwen.com/subject/wkhkhhtx.html