php实现设计模式之 简单工厂模式

时间:2023-03-08 20:12:52

作为对象的创建模式,用工厂方法代替new操作。

简单工厂模式是属于创建型模式,又叫做静态工厂方法模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。

工厂类,包含工厂方法,由参数决定实例化哪一种对象

多种类,均含同一方法,实现具体业务

多种类继承一抽象类,抽象方法其子类必须都实现

UML类图如下

php实现设计模式之    简单工厂模式

<?php
/*
* 工厂类,里面包含工厂方法,代替new操作,由参数决定创建哪一种对象
*/
class operator{
public $a,$b,$oper; public function __construct($a,$b,$oper){
$this->a = $a;
$this->b = $b;
$this->oper = $oper;
} public function getresult(){
switch ($this->oper){
case 1: $model = new add($this->a,$this->b);break;
case 2: $model = new jian($this->a,$this->b);break;
case 3: $model = new cheng($this->a,$this->b);break;
case 4: $model = new chu($this->a,$this->b);break;
}
return $model->result();
}
} /*
* 抽象类,其子类必须实现运算方法
*/
abstract class poper{
public $a,$b;
public function __construct($a,$b){
$this->a =$a;
$this->b = $b;
}
abstract function result();
} //子类,负责具体业务实现
class add extends poper{
public function result(){
return $this->a+$this->b;
}
} class jian extends poper{
public function result(){
return $this->a-$this->b;
}
} class cheng extends poper{
public function result(){
return $this->a*$this->b;
}
}
class chu extends poper{
public function result(){
if($this->b ==0){
return '除数不能为0';
}
return $this->a/$this->b;
}
}
?>

  

客户端只需要输入参数,不关心对象的创建(交给了工厂方法)。区别于策略模式,策略模式客户端自己决定使用哪一种算法类

试想一下:现在新增一个类。简单工厂模式需要写这个类,同时修改工厂类,修改工厂方法的逻辑。而策略模式只需要写这个类即可,客户端就可以替换了。

简单工厂方法所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。新增的类很多时,工厂方法逻辑判断多,蔓延维护困难。

使用场景

工厂类负责创建的对象比较少而且事先知道所有类;(一般不多于5个)
客户只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心