php设计模式之工厂方法
实现不修改原代码,扩展新功能
<?php header("Content-type:text/html;charset=utf-8"); /** * db接口 * 实现连接数据库函数conn */ interface db { function conn(); } /** * 工厂接口 * 实现创建连接函数createDb */ interface factory { function createDb(); } /** * mysql类 */ class DbMysql implements db { public function conn() { echo "连接上了mysql<br>"; } } /** * sqlite类 */ class DbSqlite implements db { public function conn() { echo "连接上了sqlite<br>"; } } /** * MysqlFactory */ class MysqlFactory implements factory { public function createDb() { return new DbMysql(); } } /** * SqliteFactory */ class SqliteFactory implements factory { public function createDb() { return new DbSqlite(); } } //不修改源代码,扩展oracle数据库 /** * oracle */ class DbOracle implements db { public function conn() { echo "连上了oracle数据库<br>"; } } /** * oracle工厂类 */ class OracleFactory implements factory { public function createDb() { return new DbOracle(); } } // 客户端调用 $factory = new MysqlFactory(); $db = $factory->createDb(); $db->conn(); $factory = new SqliteFactory(); $db = $factory->createDb(); $db->conn(); $factory = new OracleFactory(); $db = $factory->createDb(); $db->conn();
相关推荐
yangyujun 2020-08-21
jkzyx 2020-04-17
缘起宇轩阁 2019-12-30
swimmer000 2019-12-30
王志龙 2019-12-26
gougouzhang 2019-12-13
徐建岗网络管理 2011-12-18
HuangXiaoChuan 2019-03-20
一个过客 2019-03-25
machao 2019-03-21
cyAspNet 2019-07-01
Triones 2019-07-01
HavenZhao 2019-07-01
chengrile 2014-10-26
programisaart 2019-06-28
fuziwang 2019-06-28
gotea 2012-09-13