php抽象工厂模式

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();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值