設計模式簡單說應對某類問題而設計的解決方式
工廠模式:應對需求創建相應的對象
<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之設計模式(工廠、單例),包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。