Design patterns simply describe solutions designed to deal with certain types of problems
Factory pattern: Create corresponding objects in response to needs
<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>
Single case pattern: Only create an instance of an object, no more instances are allowed to be created, saving resources ( For example, database connection)
<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>
The above introduces the design patterns of PHP (factory, singleton), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.