该模式通常结合单例模式与抽象工厂使用
    服务定位器也有不好的地方,它将查找和提供所需实例类型的责任委托给了提供方
    ServiceLocator.png

    Settings.php

    1. class Settings
    2. {
    3. public static $COMMSTYPE = 'unix'
    4. }

    AppConfig.php

    1. class AppConfig
    2. {
    3. private static $instance;
    4. private CommsManager $commsManager;
    5. private __construct()
    6. {
    7. $this->init();
    8. }
    9. public static function getInstance(): self
    10. {
    11. if(empty(self::$instance)){
    12. self::instance = new self();
    13. }
    14. return self::$instance;
    15. }
    16. private function init()
    17. {
    18. switch(Settings::$COMMSTYPE){
    19. case 'unix':
    20. $this->commsManager =new UnixCommsManager();
    21. break;
    22. default:
    23. $this->commsManager = new WinCommsManager();
    24. }
    25. }
    26. public function getCommsManager(): CommsManager
    27. {
    28. return $this->commsManager;
    29. }
    30. }

    与直接进行实例化相比,它引入的依赖关系更加缓和。任何使用其服务的类都必须显式的调用这个服务定位器,这会将它们与外部系统绑定在一起。