抽象工厂模式
抽象工厂模式:提供创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类
interface IFactory
{
public function CreateOperation();#第一个产品
public function CreateOperation1();#第二个产品,可以有多个产品
}
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();
}
public function CreateOperation1(){
return new OperationSub();
}
}
class SubFactory implements IFactory
{
public function CreateOperation()
{
return new OperationSub();
}
public function CreateOperation1(){
return new OperationMul();
}
}
class MulFactory implements IFactory
{
public function CreateOperation()
{
return new OperationMul();
}
public function CreateOperation1()
{
return new OperationAdd();
}
}
class DivFactory implements IFactory
{
public function CreateOperation()
{
return new OperationDiv();
}
public function CreateOperation1()
{
return new OperationAdd();
}
}
$operFactory = new AddFactory();
$oper = $operFactory->CreateOperation();
$oper->numberA = 1;
$oper->numberB = 2;
$result = $oper->getResult();
echo $result;
总结
简单工厂模式:工厂类负责创建的对象较少,功能简单的产品
工厂方法模式:当一个类不知道它所必须创建对象的类或一个类希望由子类来指定它所创建的对象时,当类将创建对象的职责委托给多个帮助子类中得某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候
抽象工厂模式:适用于生成多个产品族、多个产品树的情景