プロトタイプ パターンは、抽象ファクトリ パターン/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); ?>
プロトタイプ モードはコードの量を減らし、オブジェクトを返すときにカスタム操作を追加できるため、非常に柔軟で便利です。ただし、プロトタイプ モードではクローン メソッドが使用されることに注意してください。クローンによって引き起こされる浅いコピーの問題に注意してください。つまり、クローン オブジェクトのプロパティにオブジェクトが含まれている場合、クローンは新しいコピーを取得しません。同じ参照。
上記は PHP オブジェクト指向開発 - プロトタイプ モードの内容です。その他の関連コンテンツについては、PHP 中国語 Web サイト (www.php.cn) をご覧ください。