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

來源:互聯網
上載者:User
原型模式是抽象原廠模式/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物件導向開發之——原型模式的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.