首页 >后端开发 >php教程 >php中工厂方法的两个特殊例子

php中工厂方法的两个特殊例子

WBOY
WBOY原创
2016-07-29 09:09:42760浏览

工厂方法,简单来说就是生成包含类的实例的一种方法。
工厂模式是最常用的实例化对象模式了,是用工厂方法代替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教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn