Blogger Information
Blog 11
fans 0
comment 0
visits 6599
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP设计模式学习笔记——简单工厂模式
青Blue的博客
Original
556 people have browsed it

实例

<?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燕十八 面向对象与设计模式

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post