实例
<?php /** * @Description: 简单工厂模式,面向接口开发 * @Author: luoxiaojin * @Date: 2020-06-29 13:38:22 * @LastEditors: luoxiaojin * @LastEditTime: 2020-06-30 10:09:53 * @FilePath: \design_patterns\l2.php */ interface Db { public function conn(); } class dbmysql implements Db { public function conn() { echo "连接上了mysql服务器"; } } class dbsqlite implements Db { public function conn() { echo "连上了sqlite"; } } // 面向接口演示 (new dbmysql)->conn(); // 简单工厂模式 class Factory { public static function createDb($type) { if ($type == 'mysql') { return new dbmysql(); } else if ($type == 'sqlite') { return new dbsqlite(); } else { throw new Exception('Error db type'); } } } Factory::createDb('sqlite')->conn();
运行实例 »
点击 "运行实例" 按钮查看在线实例
——学习参考与 bilibili燕十八 面向对象与设计模式