首頁 > 後端開發 > php教程 > php中工廠方法的兩個特殊例子

php中工廠方法的兩個特殊例子

WBOY
發布: 2016-07-29 09:09:42
原創
757 人瀏覽過

工廠方法,簡單來說就是產生包含類別的實例的一種方法。
工廠模式是最常用的實例化物件模式了,是用工廠方法取代new操作的一種模式。
這裡附上一個比較特別的例子:
我們要創造一個地球人,地球有兩種人,男人和女人:

<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>
登入後複製
').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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板