【普通工厂】
<?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>';