Blogger Information
Blog 32
fans 2
comment 2
visits 23250
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【Part1】单例模式/普通和抽象工厂模式演示(0218)
暴风战斧
Original
508 people have browsed it

【编程思路】

1、单例模式重点理解new一次就是一个新的对象;

2、普通工厂实现依赖一个工厂类,抽象工厂通过接口实现类实例化比普通工厂更抽象

【作业总结】

正如老师课程中提到的,不要怕抽象,代码越抽象越好,这次作业实实在在的感受到了接口的好处!

【代码演示】

<?php

namespace day18;

// 单例模式:创建类的唯一实例
class DataBase
{
    // 将类中的构造方法私有化,防止从外部通过new实例化这个类
    private function __construct(...$connectParams)
    {
        list($dsn, $username, $password) = $connectParams;
        self::$pdo = new \PDO($dsn, $username, $password);
    }

    // 当前类实例
    private static $pdo = null;

    // 获取当前实例
    public static function onDataBase(...$connectParams)
    {
        // 判断是否实例化,未实例化则new实例化
        if (is_null(self::$pdo)) {
            new self(...$connectParams);
        }
        // 如果实例化了,就不重复实例化,直接返回
        return self::$pdo;
    }

    // 克隆方法私有化,防止克隆当前对象
    private function __clone()
    {

    }
}

// 连接参数
$connectParams = ['mysql:host=localhost;dbname=phpedu', 'root', 'root'];
$pdo = DataBase::onDataBase(...$connectParams);
$pdo1 = DataBase::onDataBase(...$connectParams);
var_dump($pdo === $pdo1);
echo '<hr>';
print_r($pdo->query('select * from staffs')->fetchAll(\PDO::FETCH_ASSOC));

单例模式.png

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:完成的很棒
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