PHP 之设计模式学习笔记 - 工厂模式(自用)
工厂模式 就是使用一个工厂方法来替换调直接 new 对象的操作
实例:
接口,提供具体类实现
<?php
namespace App\Service\DesignPattern\Factory;
interface BicycleBase
{
//目的地 提供具体实现
public function driveTo($destination);
}
具体类实现
<?php
namespace App\Service\DesignPattern\Factory;
class Bicycle implements BicycleBase
{
public function driveTo($destination)
{
//相关计算(获取当前地址 返回当前地址与目的地的公里数、价格等) ,返回价格......
return '48公里';
}
}
工厂方法调用具体类
<?php
namespace App\Service\DesignPattern\Factory;
class Factory
{
/**
* @param string $type
* @return \Illuminate\Contracts\Foundation\Application|mixed
*/
public static function createClassName($type = 'bicycle')
{
//可以使用这种实现
//$className = ucfirst($type);
//$className = "\App\Service\DesignPattern\Factory\\" . $className;
//return new $className();
//resolve() laravel 框架辅助函数
return resolve("App\Service\DesignPattern".'\\'.ucfirst($type));
}
/**
* 第二种方法
* @param string $type
* @return Bicycle
* @throws \Exception
*/
public static function createClassName($type = 'bicycle')
{
switch ($type) {
case 'bicycle':
return new Bicycle();
break;
default:
throw new \Exception('没有该类');
}
}
}
使用:
$bicycle = Factory::createBicycle('bicycle');
//$bicycle = Factory::createClassName('bicycle');
$destination = $bicycle->driveTo('上海');
return $destination;
参数介绍:
/**
* resolve() laravel 框架给定辅助函数
* 使用服务容器解析给定名称的类和接口的实例
*/
[resolve()](https://learnku.com/docs/laravel/7.x/helpers/7486#method-resolve)