原型模式(Prototype)
Prototype原型模式是一種創建型設計模式,Prototype模式允許一個對象再創建另外一個可定制的對象,根本無需知道任何如何創建的細節,工作原理是:通過將一個原型對象傳給那個要發動創建的對象,這個要發動創建的對象通過請求原型對象拷貝它們自己來實施創建。
解決什么問題
它主要面對的問題是:“某些結構復雜的對象”的創建工作;由于需求的變化,這些對象經常面臨著劇烈的變化,但是他們卻擁有比較穩定一致的接口。
使用php提供的clone()方法來實現對象的克隆,所以Prototype模式實現一下子變得很簡單。并可以使用php的__clone() 函數完成深度克隆。
代碼實例:
- <?php
- //定義原型類接口
- interface prototype{
- public function copy();
- }
- //一個具體的業務類并實現了prototype 接口
- //以一個文本的讀寫操作類為例
- class text implements prototype{
- private $_fileUrl;
- public function __construct($fileUrl){
- $this->_fileUrl = $fileUrl;
- }
- public function write($content){
- file_put_contents($this->_fileUrl, $content);
- }
- public function read(){
- return file_get_contents($this->_fileUrl);
- }
- public function copy(){
- return clone $this;
- }
- /* 可以使用php的__clone() 函數完成深度克隆 */
- public function __clone(){
- echo 'clone...';
- }
- }
- $texter1 = new text('1.txt');
- $texter1->write('test...');
- //獲得一個原型
- $texter2 = $texter1->copy();
- echo $texter2->read();
新聞熱點
疑難解答