一、单例模式
单例模式:创建类的唯一实例,应用场景:PDO链接数据库
//单例模式
namespace _1205;
//PDO链接
class Db
{
//创建私有化静态属性
public static $pdo = null;
//构造方法私有化
private function __construct(...$params)
{
$dsn = $params[0];
$username= $params[1];
$password=$params[2];
self::$pdo = new \PDO($dsn,$username,$password);
}
public static function connect(...$params)
{
if (is_null(self::$pdo)){
new self(...$params);
}
return self::$pdo;
}
// 禁用克隆魔术方法
private function __clone()
{
}
}
$params = ['mysql:host=localhost;dbname=movies','root','root'];
$pdo = Db::connect(...$params);
$sql = "SELECT * FROM `category` WHERE `cate_id` > :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id'=>20]);
//print_r($stmt->debugDumpParams());
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
echo '<pre>'.print_r($row,true);
}
代码运行效果:
二、工厂模式
工厂模式:用于批量创建类的实例/对象
//工厂模式:用于批量创建类的实例/对象
namespace _1205;
class Test1
{
public function __construct($arg1)
{
echo '对象创建成功,参数是:'.$arg1;
}
}
class Test2
{
public function __construct($arg1,$arg2)
{
echo '对象创建成功,参数是:'.implode(', ', [$arg1, $arg2]);
}
}
class Test3
{
public function __construct($arg1,$arg2,$arg3)
{
echo '对象创建成功,参数是:'.implode(', ', [$arg1, $arg2, $arg3]);
}
}
class Factory
{
public static function create($className,...$argments)
{
return new $className(...$argments);
}
}
Factory::create(Test1::class,100);
echo '<hr>';
Factory::create(Test2::class,100,200);
echo '<hr>';
Factory::create(Test3::class,100,200,300);
运行效果:
三、依赖注入
依赖注入:解决对象调用之间的耦合问题
demo.php
namespace _1205;
require 'Maker.php';
require 'Product.php';
require 'Container.php';
//控制器
class Show2
{
//输出商品与制造商
public function show(Product $product, Maker $maker){
//制造商注入到产品类
return $product->get($maker);
}
}
//将类实例绑定到容器中并实例化返回
$container = new Container();
//将实例化代码绑定到容器中
$container->bind('product',function (){return new Product();});
$container->bind('maker',function (){return new Maker();});
//创建类实例并返回
$product = $container->make('product');
$maker = $container->make('maker');
//客户端调用
$show = new Show2();
echo '容器:'.$show->show($product,$maker);
Product.php
namespace _1205;
//商品类
class Product
{
public function get(Maker $maker){
return '该手机是由:'. $maker->get() .'生产的';
}
}
Maker.php
namespace _1205;
//制造商
class Maker
{
public function get()
{
return '华为';
}
}
Container.php(服务容器)
//容器类
namespace _1205;
use Closure; //引入闭包类型
class Container
{
//创建容器数组,里面存储创建对象的方法
protected $instance = [];
//存进去:将类实例化的过程绑定到容器中,$alias是类名,$process是实例化代码=new Product();
public function bind($alias,Closure $process){
$this->instance[$alias] = $process;
}
//取出来:取出保存在容器中的实例化过程的闭包,并执行它,就是上面绑定的$process
public function make($alias,$params = []){
//$this->instance[$alias]是一个闭包函数
//$this->instance[$alias]() 返回的是一个类实例对象_1205\Product
return $this->instance[$alias]();
}
}
运行效果:
四、工厂方法实例
//工厂模式
namespace base;
use base\inc1\Car;
use base\inc1\Train;
use base\inc1\Plane;
require __DIR__ . '/autoload.php';
class Factory
{
protected static $in = null;
public static function getInfo($className){
switch (strtolower($className)){
case 'car':
self::$in = new Car();
break;
case 'train':
self::$in = new Train();
break;
case 'plane':
self::$in = new Plane();
}
return self::$in;
}
}
class Travel2
{
private $vehicle;
public function __construct($vehicle)
{
$this->vehicle = Factory::getInfo($vehicle);
}
public function travelModel(){
return $this->vehicle->drive().' : 去旅行';
}
}
echo (new Travel2('car'))->travelModel() . '<br>';
echo (new Travel2('train'))->travelModel() . '<br>';
echo (new Travel2('plane'))->travelModel() . '<br>';
五、面向接口编程
Car.php
namespace base\inc2;
class Car implements iVehicle
{
public function drive(){
return '开汽车';
}
}
Plane.php
namespace base\inc2;
class Plane implements iVehicle
{
public function drive(){
return '坐飞机';
}
}
Train.php
namespace base\inc2;
class Train implements iVehicle
{
public function drive(){
return '坐火车';
}
}
iVehicle.php(接口)
namespace base\inc2;
interface iVehicle
{
public function drive();
}
autoload.php
spl_autoload_register(function ($className){
$path = str_replace('\\','/',$className);
include dirname(__DIR__) . DIRECTORY_SEPARATOR.$path.'.php';
});
Travel.php
namespace base;
use base\inc2\Car;
use base\inc2\iVehicle;
use base\inc2\Train;
use base\inc2\Plane;
require __DIR__ . '/autoload.php';
class Travel3
{
public $vehicle;
public function __construct(iVehicle $vehicle)
{
$this->vehicle = $vehicle;
}
public function travelMedol(){
return $this->vehicle->drive() .' : 3-去旅行';
}
}
echo (new Travel3(new Car()))->travelMedol().'<br>';
echo (new Travel3(new Train()))->travelMedol().'<br>';
echo (new Travel3(new Plane()))->travelMedol().'<br>';
手写:
总结:
- 单例模式:创建唯一实例,典型场景:用于数据库连接
- 工厂模式:用于批量创建类的实例/对象
- 依赖注入:解决对象调用之间的耦合,主要通过构造方法注入
- 服务容器:将类的实例和实例化方法统一管理,并在类中提供绑定方法和执行方法(简称存进去,取出来)
- 面向接口编程:有点抽象。。。