以前做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();