工厂模式通常用来返回类似接口的不同的类,工厂的一种常见用法就是创建多态的提供者。
通常工厂模式有一个关键的构造,即一般被命名为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教程有兴趣的朋友有所帮助。