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

【普通工厂】

<?php

namespace day18;

// 导入商城类
use me\base\inc01\Jd;
use me\base\inc01\Duo;
use me\base\inc01\Tmall;

// 自动加载
require __DIR__ . '/autoload.php';

// 工厂类,将依赖对象通过它实例化
class Factory
{
    private static $instance = null;

    public static function getInstance($shop)
    {
        switch (strtolower($shop)) {
            case 'jd':
                self::$instance = new Jd();
                break;
            case 'duo':
                self::$instance = new Duo();
                break;
            case 'tmall':
                self::$instance = new Tmall();
                break;
        }
        return self::$instance;
    }
}

// 商城类
class Shopping1
{
    // 商城平台
    private $shop = null;

    // 由工厂类完成实例化依赖对象的过程
    public function __construct($shop)
    {
        // 只需依赖一个工厂类即可
        $this->shop = Factory::getInstance($shop);
    }

    // 调用外部依赖对象的方法
    public function goShopping() {
        return $this->shop->shop() . ' >>> 省钱更省心!';
    }
}

// 客户端调用
echo (new Shopping1('jd'))->goShopping() . '<br>';
echo (new Shopping1('duo'))->goShopping() . '<br>';
echo (new Shopping1('tmall'))->goShopping() . '<br>';

普通工厂.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