//serviceLocator
interface Service
{
public function getName();
public function execute();
}
class Service1 implements Service
{
public function execute()
{
echo 'Executing Service1' . "<br />";
}
public function getName()
{
return "Service1" . "<br />";
}
}
class Service2 implements Service
{
public function execute()
{
echo 'Executing Service2' . "<br />";
}
public function getName()
{
return "Service2" . "<br />";
}
}
class InitialContext
{
public function lookup($jndiName)
{
//返回0就是相等
if (!strcasecmp('SERVICE1', $jndiName)) {
echo "Looking up and creating a new Service1 object" . "<br />";
return new Service1();
} else if (!strcasecmp('SERVICE2', $jndiName)) {
echo "Looking up and creating a new Service2 object" . "<br />";
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' . "<br />";
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
网友评论