工厂方法规避了简单工厂的违反开放封闭原则;
结构:
有interface和abstract产品父类;
有实现父类的产品子类;
有interface和abstract工厂父类;
有实现父类的工厂子类;
示例:
Operation.php
<?php
namespace mulfactory;
abstract class Operation
{
protected $numberA =0;
protected $numberB =0;
abstract public function getResult();
public function setNumberA($number)
{
return $this->numberA=$number;
}
public function setNumberB($number)
{
return $this->numberB=$number;
}
}
Add.php
<?php
namespace mulfactory;
class Add extends Operation
{
public function getResult()
{
$result = $this->numberA+$this->numberB;
return $result;
}
}
Div.php
<?php
namespace mulfactory;
class Div extends Operation
{
public function getResult()
{
if($this->numberB != 0){
$result = $this->numberA/$this->numberB;
return $result;
}else{
throw new \InvalidArgumentException('除数不能为零');
}
}
}
Mul.php
<?php
namespace mulfactory;
class Mul extends Operation
{
public function getResult()
{
$result = $this->numberA*$this->numberB;
return $result;
}
}
Sub.php
<?php
namespace mulfactory;
class Sub extends Operation
{
public function getResult()
{
$result = $this->numberA - $this->numberB;
return $result;
}
}
Factory.php
<?php
namespace mulfactory;
abstract class Factory
{
abstract public function create();
}
AddFactory.php
<?php
namespace mulfactory;
class AddFactory extends Factory
{
public function create()
{
return new Add();
}
}
DivFactory.php
<?php
namespace mulfactory;
class DivFactory extends Factory
{
public function create()
{
return new Div();
}
}
MulFactory.php
<?php
namespace mulfactory;
class MulFactory extends Factory
{
public function create()
{
return new Mul();
}
}
SubFactory.php
<?php
namespace mulfactory;
class SubFactory extends Factory
{
public function create()
{
return new Sub();
}
}
index.php
<?php
require __DIR__.'/../Loader.php';
spl_autoload_register('Loader::autoload');//注册自动加载
$factory = new \mulfactory\AddFactory();
$operation = $factory->create();
$operation->setNumberA(1);
$operation->setNumberB(2);
$result = $operation->getResult();
echo $result;