工廠模式通常用來傳回類似介面的不同的類,工廠的常見用法就是創建多態的提供者。
通常工廠模式有一個關鍵的構造,即一般被命名為factory的靜態方法。這個靜態方法可以接受任意數量的參數,並且必須傳回一個物件。
<spanmicrosoft yahei><span>interface</span><span> IDatabase { //...</span><span>public</span> <span>function</span> query(<span>$sql</span><span>);</span><span> } </span><span>class</span><span> DBFactory { </span><span>public</span> <span>static</span> <span>function</span> create(<span>$type</span><span>){ </span><span>$db</span> = <span>null</span><span>; </span><span>switch</span> (<span>$type</span><span>) { </span><span>case</span> 'mysql': <span>$db</span> = <span>new</span> <span>Mysql</span>(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>case</span> 'sqlite': <span>$db</span> = <span>new</span> Sqlite(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>case</span> 'pgsql': <span>$db</span> = <span>new</span> PGsql(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>default</span>: <span>#</span><span> code...</span> <span>break</span><span>; } </span><span>return</span> <span>$db</span><span>; } } </span><span>class</span> <span>Mysql</span> <span>implements</span><span> IDatabase { </span><span>//... </span><span>public</span> <span>function</span> query(<span>$sql</span><span>){ }</span><span> } </span><span>/*</span><span>*other class ...</span><span>*/</span></spanmicrosoft>
<spanmicrosoft yahei><span>$db</span> = DBFactory::create('mysql'<span>); </span><span>$db</span>->query('show database');</spanmicrosoft>
以上就介紹了php中的設計模式:工廠模式,包括了php工廠模式的內容,希望對PHP教程有興趣的朋友有幫助。