php设计模式-简单工厂

简单工厂

//公共接口
interface db(){
    function conn(){

    }
}

//服务端
class dbmysql implements db {
    public function conn(){
        echo '连接上了mysql';
    }
}

class dbsqlite implements db {
    public function conn(){
        echo '连接上了sqlite';
    }
}

class Factory {
    public static function createDB($type){
        if ($type == 'mysql') {
            return new dbmysql();
        } else if ($type == 'sqlite') {
            return new dbsqlite();
        } else {
            throw new \Exception('db type error');
        }
    }
}

//客户端
$db = Factory::createDB('mysql');
$db->conn();

$db = Factory::createDB('sqlite');
$db->conn();

面向对象设计法则,开闭原则:对于修改是封闭的,对于扩展是开放的

    原文作者:github_39592293
    原文地址: https://blog.csdn.net/github_39592293/article/details/80176956
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞