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

PHP设计模式--工厂模式

WBOY
WBOYOriginal
2016-06-23 13:16:07875browse

<?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/>';

 

Statement:
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