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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值