php抽象工厂模式简单介绍
1.工厂模式就相当于是一个超级工厂
2.抽象工厂模式,每个工厂只负责创建一个对象不需要我们指定相关的类
3.面向对象的开闭原则,可以增加类但是尽量不要去修改类
我们下面看下上一节简单工厂模式的代码
interface Shape{
public function draw();
}
//实现产品的具体类
class Rectangle implements Shape{
public function draw(){
echo 'Insade Rectangle::draw() method。<br/>';
}
}
class Sqare implements Shape{
public function draw(){
echo 'Insade Sqare::draw() method。<br/>';
}
}
class Circle implements Shape{
public function draw(){
echo 'Imsade Circle::draw() mothod。<br/>';
}
}
//创建一个工厂生成给定信息的实体对象
class ShapeFactory{
public function getShape($shape_type){
if($shape_type==''){
return null;
}
if(trim($shape_type)=='Circle'){
return new Circle();
}
if(trim($shape_type)=='Sqare'){
return new Sqare();
}
if(trim($shape_type)=='Rectangle'){
return new Rectangle();
}
return null;
}
}
//创建一个客户端调用工厂的方法
class Client{
public function __construct(){
$ShapeFactory = new ShapeFactory();
$Rectangle = $ShapeFactory->getShape('Rectangle');
$Rectangle->draw();
$Sqare = $ShapeFactory->getShape('Sqare');
$Sqare->draw();
$Circle = $ShapeFactory->getShape('Circle');
$Circle->draw();
}
}
$client = new Client();
我们调用工厂的getShape()方法传递不同的形参来获取不同产品的对象假如我又新增了一个产品
是不是又的在getShape()方法里面增加判断
class Rectangle1 implements Shape{
public function draw(){
echo 'Insade Rectangle1::draw() method。<br/>';
}
}
class ShapeFactory{
public function getShape($shape_type){
if($shape_type==''){
return null;
}
if(trim($shape_type)=='Circle'){
return new Circle();
}
if(trim($shape_type)=='Sqare'){
return new Sqare();
}
if(trim($shape_type)=='Rectangle'){
return new Rectangle();
}
if(trim($shape_type==“Rectangle1'')){
return new Rectangle();
}
return null;
}
}
这样我们直接把工厂抽离出来每个工厂只负责生产一个单一的产品
interface ShapeFactory{
function getOgj();
}
//负责生产产品1
ShapeFactory1 implements ShapeFactory{
public function getOgj(){
return new 产品1();
}
}
//负责生产产品2
ShapeFactory2 implements ShapeFactory{
public function getOgj(){
return new 产品2();
}
}