首頁  >  文章  >  後端開發  >  php物件導向開發之-原型模式

php物件導向開發之-原型模式

黄舟
黄舟原創
2016-12-29 11:16:411649瀏覽

原型模式是抽象工廠模式/content/10866786.html強大的變形,簡單來說,它將抽象工廠模式中的若干工廠類別組合合併成一個中控類,由中控類別開啟負責產生物件。

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

class carEngine implements engineNorms{

	public function engine(){
		return &#39;汽车引擎&#39;;
	}

}

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

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

class carBody implements bodyNorms{

	public function body(){
		return &#39;汽车车身&#39;;
	}

}

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

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

class carWhell implements whellNorms{

	public function whell(){
		return &#39;汽车轮子&#39;;
	}

}

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

//原型工厂
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[&#39;engine&#39;]=$carFactory->getEngineNorms()->engine();
$car[&#39;body&#39;]=$carFactory->getBodyNorms()->body();
$car[&#39;whell&#39;]=$carFactory->getWhellNorms()->whell();
print_r($car);

$busFactory=new factory(new busEngine(),new busBody(),new busWhell());
$bus[&#39;engine&#39;]=$busFactory->getEngineNorms()->engine();
$bus[&#39;body&#39;]=$busFactory->getBodyNorms()->body();
$bus[&#39;whell&#39;]=$busFactory->getWhellNorms()->whell();
print_r($bus);
?>

原型模式減少了程式碼量,而且在回傳物件時,更是可以加入自訂的操作,十分的靈活方便。但要注意的是,原型模式使用了clone方法,請注意clone產生的淺複製問題,即,被clone的對象的屬性中包含對象,那clone得到的將不是新的複本,而是相同的引用。

 以上就是php物件導向開發之-原型模式的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn