设计模式简单说应对某类问题而设计的解决方式
工厂模式:应对需求创建相应的对象
<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教程有兴趣的朋友有所帮助。