实例
<?php /** * @Description: 完全工厂模式 * @Author: luoxiaojin * @Date: 2020-06-29 14:27:50 * @LastEditors: luoxiaojin * @LastEditTime: 2020-06-29 14:49:22 * @FilePath: \design_patterns\l3.php */ interface Factory{ public function createDb(); } interface Db { public function conn(); } class DbMySQL implements Db { public function conn() { echo "连接上了mysql服务器"; } } class DbSqLite implements Db { public function conn() { echo "连上了sqlite"; } } class MysqlFactory implements Factory{ public function createDb(){ return new DbMySQL(); } } class SqliteFactory implements Factory{ public function createDb(){ return new DbSqLite(); } } $fact = new MysqlFactory(); $db = $fact->createDb(); $db->conn(); $fact = new SqliteFactory(); $db = $fact->createDb(); $db->conn(); // 拓展oracle类 class DbOracle implements Db{ public function conn(){ echo "连接上了Oracle数据库"; } } class OracleFActory implements Factory{ public function createDb(){ return new DbOracle(); } } // 调用拓展出来的类 (new OracleFActory())->createDb()->conn();
运行实例 »
点击 "运行实例" 按钮查看在线实例
——学习参考与 bilibili燕十八 面向对象与设计模式