本章通过对工厂模式和依赖注入模式的学习,了解了工厂模式主要是通过在工厂类中统一创建并返回其他类的对象;依赖注入主要通过构造函数或者普通方法传对象参数的方式,把具体对象注入到方法中。通过两种设计模式,解决了原先在类中直接创建其他类所导致的高耦合问题,实现解耦。实现代码如下:
工厂模式代码:
Factory.php
<?php namespace app\index\controller; class Factory { public static function create($class) { switch (strtolower($class)) { case 'boy': return new Boy(); break; case 'girl': return new Girl(); break; } } } class Boy { public function show() { return '我是男孩'; } } class Girl { public function show() { return '我是女孩'; } }
Index.php调用:
<?php namespace app\index\controller; use think\Request; class Index { public function index() { // dump(DataBase::getInstance()); //单例模式获取数据库配置信息 return Factory::create('girl')->show(); //工厂模式创建类及调用类方法 //通过依赖注入实现解耦 // $girl=new Person(); // $injection=new Injection($girl); // return $injection->getAbility($girl); } public function hello($name = 'ThinkPHP5') { return 'hello,' . $name; } /** * 获取请求参数 * @param Request 请求的参数 */ public function getParam(Request $request) { dump($request->param()); } }
效果图:
依赖注入实现解耦代码:
Person.php
<?php /** * Created by PhpStorm. * User: Jizp * Date: 2019-2-21 * Time: 10:42 */ namespace app\index\controller; class Person { public function sing() { return '唱歌'; } public function dance() { return '跳舞'; } }
Injection.php
<?php namespace app\index\controller; class Injection { private $done; //构造函数依赖注入 public function __construct(Person $gril) { $this->done=$gril->sing(); } public function getDone() { return '我可以'.$this->done; } //普通方法依赖注入 public function getAbility(Person $girl) { return $this->getDone().',也可以'.$girl->dance(); } }
Index.php调用页面:
<?php namespace app\index\controller; use think\Request; class Index { public function index() { // dump(DataBase::getInstance()); //单例模式获取数据库配置信息 // return Factory::create('girl')->show(); //工厂模式创建类及调用类方法 //通过依赖注入实现解耦 $girl=new Person(); $injection=new Injection($girl); return $injection->getAbility($girl); } public function hello($name = 'ThinkPHP5') { return 'hello,' . $name; } /** * 获取请求参数 * @param Request 请求的参数 */ public function getParam(Request $request) { dump($request->param()); } }
效果图: