php 工厂方法模式

#使用工厂方法模式是不知道要创建类的对象有哪些.
interface IFactory
{
public function CreateOperation();#工厂方法模式只有单个产品

}

class Operation extends Model
{

private $numberA;
private $numberB;


public function getResult(){

$result = 0;

return $result;

}

public function getNumberA(){

return $this->numberA;
}
public function setNumberA($numberA){

$this->numberA = $numberA;

}

public function getNumberB(){

return $this->numberB;
}
public function setNumberB($numberB){

$this->numberB = $numberB;

}




}

class OperationAdd extends  Operation
{

public function getResult()
{
$result = 0 ;

$result = $this->numberA + $this->numberB;

return $result;


}

}


class OperationSub extends Operation
{

public function getResult()
{
$result = 0;

$result = $this->numberA - $this->numberB;

return $result;
}

}

class OperationMul extends  Operation
{
public function getResult(){

$result = 0;

$result = $this->numberA * $this->numberB;

return $result;

}

}
class OperationDiv extends  Operation
{
public function getResult(){

$result = 0;
if ($this->numberA == 0){

throw new HttpException("除数不能为0");
}

$result = $this->numberA / $this->numberB;

return $result;
}

}

class AddFactory implements IFactory
{

public function CreateOperation()
{
return new OperationAdd();
}


}

class SubFactory implements IFactory
{

public function CreateOperation()
{
return new OperationSub();
}

}

class MulFactory  implements IFactory
{

public function CreateOperation()
{
return new OperationMul();
}

}

class DivFactory  implements IFactory
{

public function CreateOperation()
{
return new OperationDiv();
}

}

$operFactory = new AddFactory();

$oper = $operFactory->CreateOperation();

$oper->numberA = 1;

$oper->numberB = 2;

$result = $oper->getResult();

echo $result;

简单工厂和工厂方法的区别:简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,但是如果要添加新的功能,就要修改里面的case条件修改原有的类,这样违背了开放-封闭原则。工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化
那个类。工厂方法使一个类的实例化延迟到其子类。
工厂方法模式实现时,客户端需要决定实例化那一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行
posted on 2018-02-05 18:22  paulversion  阅读(180)  评论(0编辑  收藏  举报