服务定位器模式

//serviceLocator
interface Service
{
    public function getName();
    public function execute();
}

class Service1 implements Service
{
    public function execute()
    {
        echo 'Executing Service1' . "
"; } public function getName() { return "Service1" . "
"; } } class Service2 implements Service { public function execute() { echo 'Executing Service2' . "
"; } public function getName() { return "Service2" . "
"; } } class InitialContext { public function lookup($jndiName) { //返回0就是相等 if (!strcasecmp('SERVICE1', $jndiName)) { echo "Looking up and creating a new Service1 object" . "
"; return new Service1(); } else if (!strcasecmp('SERVICE2', $jndiName)) { echo "Looking up and creating a new Service2 object" . "
"; return new Service2(); } return null; } } class Cache { private $services; public function Cache() { $this->services = []; } public function getService($serviceName) { foreach ($this->services as $service) { if (!strcasecmp($service->getName(), $serviceName)) { echo 'Returning cached ' . $serviceName . ' object' . "
"; return $service; } } return null; } public function addService($newService) { $exists = false; foreach ($this->services as $service) { if(!strcasecmp($service->getName(),$newService->getName())){ $exists = true; } } if ($exists) { $this->services[] = $newService; } } } class ServiceLocator { private static $cache = null; public function __construct() { if (self::$cache == null) { self::$cache = new Cache(); } } public function getService($jndiName) { $service = self::$cache->getService($jndiName); if ($service != null) { return $service; } $context = new InitialContext(); $service1 = $context->lookup($jndiName); self::$cache->addService($service1); return $service1; } } $ServiceLocator = new ServiceLocator; $service = $ServiceLocator->getService("Service1"); $service->execute(); $service = $ServiceLocator->getService("Service2"); $service->execute(); $service = $ServiceLocator->getService("Service1"); $service->execute(); $service = $ServiceLocator->getService("Service2"); $service->execute();

参考文章 http://www.runoob.com/design-pattern/service-locator-pattern.html

你可能感兴趣的:(服务定位器模式)