解釋
服務定位器用於管理一個系統中的所有服務。
結構中包含的角色
- 抽象資源依賴(AbstractResourceDependent)
- 具體資源依賴(ResourceDependent)
- 服務定位器(ServiceLocator)
- 快取(Cache)
最小可表達程式碼
interface AbstractResourceDependent {}
class ResourceDependent implements AbstractResourceDependent {}
class ServiceLocator
{
private static $cache = [];
public static function getService(String $jndiName)
{
$service = self::$cache[$jndiName];
if (null == $service) {
if (AbstractResourceDependent::class == $jndiName) {
$service = new ResourceDependent();
}
self::$cache[$jndiName] = $service;
}
return $service;
}
}
class Resource
{
private $abstractResourceDependent;
public function __construct()
{
$this->abstractResourceDependent = ServiceLocator::getService(AbstractResourceDependent::class);
}
}
實際應用場景
- Yii2.0的Application和Module都是繼承了yii\di\ServiceLocator
本作品採用《CC 協議》,轉載必須註明作者和本文連結