首頁 > 後端開發 > php教程 > PHP之設計模式(工廠、單例)

PHP之設計模式(工廠、單例)

WBOY
發布: 2016-07-29 09:02:23
原創
918 人瀏覽過

設計模式簡單說應對某類問題而設計的解決方式


工廠模式:應對需求創建相應的對象

<code><span><span>class</span><span>factory</span>{</span><span><span>function</span><span>__construct</span><span>(<span>$name</span>)</span>{</span><span>if</span>(file_exists(<span>'./'</span>.<span>$name</span>.<span>'.class.php'</span>)){
            <span>return</span><span>new</span><span>$name</span>;
        }<span>else</span>{
            <span>die</span>(<span>'not exist'</span>);
        }
    }
}</code>
登入後複製

單例模式:只創建一個對象的實例,不允許再創建實例,節約資源(例如資料庫的連線)

<code><span><span>class</span><span>instance</span>{</span><span>public</span><span>$val</span> = <span>10</span>;
    <span>private</span><span>static</span><span>$instance</span> ;
    <span>private</span><span><span>function</span><span>__construct</span><span>()</span>{</span>}
    <span>private</span><span><span>function</span><span>__clone</span><span>()</span>{</span>}
    <span>//设置为静态方法才可被类调用</span><span>public</span><span>static</span><span><span>function</span><span>getInstance</span><span>()</span>{</span><span>/*if(!isset(self::$instance)){
            self::$instance = new self;
        }*/</span><span>if</span>(!<span>isset</span>(instance::<span>$instance</span>)){
            instance::<span>$instance</span> = <span>new</span><span>self</span>;
        }
        <span>return</span> instance::<span>$instance</span>;
    }
}

<span>$obj_one</span> = instance::getInstance();
<span>$obj_one</span>->val = <span>20</span>;
<span>//clone可以调用__clone()克隆即new出一个新的的对象</span><span>//$obj_two = clone $obj_one;</span><span>$obj_two</span> = instance::getInstance();
<span>echo</span><span>$obj_two</span>->val;
<span>echo</span><span>'<p>'</p></span>;
var_dump(<span>$obj_one</span>,<span>$obj_two</span>);</code>
登入後複製

PHP之設計模式(工廠、單例)

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介紹了PHP之設計模式(工廠、單例),包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板