原型模式是抽象工厂模式/content/10866786.html强大的变形,简单来说,它将抽象工厂模式中的若干工厂类组合合并成一个中控类,由中控类开负责生成对象。

<?php
//生产引擎的标准
interface engineNorms{
	function engine();
}

class carEngine implements engineNorms{

	public function engine(){
		return '汽车引擎';
	}

}

class busEngine implements engineNorms{
	
	public function engine(){
		return '巴士车引擎';
	}
	
}

//生产车身的标准
interface bodyNorms{
	function body();
}

class carBody implements bodyNorms{

	public function body(){
		return '汽车车身';
	}

}

class busBody implements bodyNorms{
	
	public function body(){
		return '巴士车车身';
	}
	
}

//生产车轮的标准
interface whellNorms{
	function whell();
}

class carWhell implements whellNorms{

	public function whell(){
		return '汽车轮子';
	}

}

class busWhell implements whellNorms{
	
	public function whell(){
		return '巴士车轮子';
	}
	
}

//原型工厂
class factory{

	private $engineNorms;
	private $bodyNorms;
	private $whellNorms;
	
	public function __construct(engineNorms $engineNorms,bodyNorms $bodyNorms,whellNorms $whellNorms){
		$this->engineNorms=$engineNorms;
		$this->bodyNorms=$bodyNorms;
		$this->whellNorms=$whellNorms;
	}
	
	public function getEngineNorms(){
		return clone $this->engineNorms;
	}
	
	public function getBodyNorms(){
		return clone $this->bodyNorms;
	}
	
	public function getWhellNorms(){
		return clone $this->whellNorms;
	}

}
$carFactory=new factory(new carEngine(),new carBody(),new carWhell());
$car['engine']=$carFactory->getEngineNorms()->engine();
$car['body']=$carFactory->getBodyNorms()->body();
$car['whell']=$carFactory->getWhellNorms()->whell();
print_r($car);

$busFactory=new factory(new busEngine(),new busBody(),new busWhell());
$bus['engine']=$busFactory->getEngineNorms()->engine();
$bus['body']=$busFactory->getBodyNorms()->body();
$bus['whell']=$busFactory->getWhellNorms()->whell();
print_r($bus);
?>
登录后复制

原型模式减少了代码量,而且在返回对象时,更是可以加入自定义的操作,十分的灵活方便。但要注意的是,原型模式使用了clone方法,请注意clone产生的浅复制问题,即,被clone的对象的属性中包含对象,那clone得到的将不是新的复本,而是相同的引用。

以上就是php面向对象开发之——原型模式的内容,更多相关内容请关注Work网(www.php.cn)!


09-02 13:52