Home > Backend Development > PHP Tutorial > PHP设计模式--工厂模式

PHP设计模式--工厂模式

WBOY
Release: 2016-06-23 13:16:07
Original
908 people have browsed it

<?php/** * 工厂模式 * 提供获取某个对象的新实例的一个接口,同时使调用代码避免确定实际实例化基类的步骤。 *  * 工厂类用于创建不同类的实例,并将其返回。 *//** * 服务端开始 */interface DB{    function conn();}interface Factory{    function createDB();}//class MysqlDB implements DB{    public function conn() {        echo '连接上Mysql...';    }}//class SqliteDB implements DB{    public function conn() {        echo '连接上Sqlite...';    }}//class MysqlFactory implements Factory{    public function createDB() {        return new MysqlDB();    }}//class SqliteFactory implements Factory{    public function createDB() {        return new SqliteDB();    }}/** * 客户端开始 *///连接Mysql$fact = new MysqlFactory();$db = $fact->createDB();$db->conn();echo '<br/>';//连接Sqlite$fact = new SqliteFactory();$db = $fact->createDB();$db->conn();echo '<br/>';/** * 扩展:添加Oracle连接 */class OracleDB implements Db{    function conn() {        echo '连接上Oracle....';    }}class OracleFactory implements Factory{    public function createDB() {        return new OracleDB();    }}//连接Oracle$fact = new OracleFactory();$db = $fact->createDB();$db->conn();echo '<br/>';
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template