php 工廠模式

以前做google接口時看到google的接口sdk中 很多帶factory的類 一直不明白到底幹什麼用  現在看了網友的文章有所感慨 特記錄

所謂工廠模式就是:遇到需求暫不明確(不知道有多少操作)的時候用到的設計模式。

首先一個操作類型抽象類用於獲值賦值。

<?php
    /**
     * Created by PhpStorm.
     * User: antion
     * Date: 2018/10/9
     * Time: 11:34
     * Var:操作類型抽象類
     */
    abstract class Operation
    {
        protected $numberA = 0;
        protected $numberB = 0;
        abstract function getResult();
        public function setNumberA($number)
        {
            $this->numberA = $number;
        }
        public function setNumberB($number)
        {
            $this->numberB = $number;
        }
    }

在之後是操作方法,比如加法。

<?php
    /**
     * Created by PhpStorm.
     * User: antion
     * Date: 2018/10/9
     * Time: 11:38
     * Var:四則運算加法
     */
    class Add extends Operation
    {
        public function getResult()
        {
            return $this->numberA + $this->numberB;
        }
    }

這時候正常情況是直接寫一個調用方法用它,但是我們的需求暫時不明確,所以要有一個統籌所有操作的類。也就是工廠類

<?php
    /**
     * Created by PhpStorm.
     * User: antion
     * Date: 2018/10/9
     * Time: 11:40
     * Var:工廠類.
     */
    class Factory
    {
        public function create($operate)
        {
            switch ($operate) {
                case '+':
                    $result = new Add();
                    break;
                default:
                    throw new \InvalidArgumentException('暫不支持的運算');
            }
            return $result;
        }
    }

這時候在寫調用方法 就很清晰明瞭了。

<?php
    /**
     * Created by PhpStorm.
     * User: antion
     * Date: 2018/10/9
     * Time: 11:36
     * Var:客戶端
     */
    include_once "Operation.php";
    include_once "Factory.php";
    include_once "Add.php";
    class Client
    {
        public function test()
        {
            $factory = new Factory();
            $operation = $factory->create('+');
            $operation->setNumberA(1);
            $operation->setNumberB(2);
            $result = $operation->getResult();
            echo $result;
        }
    }
    $client = new Client();
    $client->test();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章