Factory method, simply put, is a method to generate instances of classes.
The factory pattern is the most commonly used instantiation object pattern. It is a pattern that uses factory methods to replace the new operation.
Here is a special example:
We want to create an earthling. There are two kinds of people on earth, men and women:
<code><span><span><?php</span><span>//实现工厂方法</span><span><span>interface</span><span>abstracted</span>{</span><span>public</span><span><span>function</span><span>realCreate</span><span>()</span>;</span> } <span>//女人类</span><span><span>class</span><span>Wuman</span>{</span><span>public</span><span><span>function</span><span>action</span><span>()</span>{</span><span>echo</span><span>"这是女人"</span>; } } <span>//男人类</span><span><span>class</span><span>Man</span>{</span><span>public</span><span><span>function</span><span>action</span><span>()</span>{</span><span>echo</span><span>"这是男人"</span>; } } <span>//创建女人</span><span><span>class</span><span>womanCreator</span><span>implements</span><span>abstracted</span>{</span><span>public</span><span>$chromosome</span>;<span>//染色体</span><span>public</span><span><span>function</span><span>realCreate</span><span>()</span>{</span><span>if</span>(<span>$this</span>->chromosome == <span>"xx"</span>){ <span>return</span><span>new</span> Wuman(); } } } <span>//创建男人</span><span><span>class</span><span>manCreator</span><span>implements</span><span>abstracted</span>{</span><span>public</span><span>$chromosome</span>;<span>//染色体</span><span>public</span><span><span>function</span><span>realCreate</span><span>()</span>{</span><span>if</span>(<span>$this</span>->chromosome == <span>"xy"</span>){ <span>return</span><span>new</span> Man(); } } } <span>//人类工厂</span><span><span>class</span><span>PersonFactory</span>{</span><span>public</span><span><span>function</span><span>create</span><span>(<span>$category</span>)</span>{</span><span>$method</span> = <span>"{$category}Creator"</span>; <span>return</span><span>$create</span> = <span>new</span><span>$method</span>(); } } <span>$create</span> = <span>new</span> PersonFactory();<span>//创造人类</span><span>$instance</span> = <span>$create</span>->create(<span>'woman'</span>);<span>//创造女人</span><span>$instance</span>->chromosome = <span>"xx"</span>;<span>//女性染色体</span><span>$instance</span>->realCreate()->action(); <span>?></span></span></span></code>
The above introduces two special examples of factory methods in PHP, including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.