服务定位器模式

服务定位器模式(Service Locator Pattern)用在我们想使用 JNDI 查询定位各种服务的时候。考虑到为某个服务查找 JNDI 的代价很高,服务定位器模式充分利用了缓存技术。在首次请求某个服务时,服务定位器在 JNDI 中查找服务,并缓存该服务对象。当再次请求相同的服务时,服务定位器会在它的缓存中查找,这样可以在很大程度上提高应用程序的性能。以下是这种设计模式的实体。

服务(Service) - 实际处理请求的服务。对这种服务的引用可以在 JNDI 服务器中查找到。

Context / 初始的 Context - JNDI Context 带有对要查找的服务的引用。

服务定位器(Service Locator) - 服务定位器是通过 JNDI 查找和缓存服务来获取服务的单点接触。

缓存(Cache) - 缓存存储服务的引用,以便复用它们。

客户端(Client) - Client 是通过 ServiceLocator 调用服务的对象。


服务定位器模式的实例

定义多种服务

class Service1 {
execute(){
console.log("Executing Service1");
}
getName() {
return "Service1";
}
}
class Service2 {
execute(){
console.log("Executing Service2");
}
getName() {
return "Service2";
}
}

定义查询服务功能

class InitialContext {
lookup(jndiName){
switch(jndiName.toUpperCase()) {
case "SERVICE1":
console.log("Looking up and creating a new Service1 object");
return new Service1();
case "SERVICE2":
console.log("Looking up and creating a new Service2 object");
return new Service2();
default:
return null;
}
}
}

定义服务缓存

class Cache {
constructor(){
this.services = [];
}
getService(serviceName){
for (const service of this.services) {
if(service.getName().toUpperCase()==serviceName.toUpperCase()){
console.log("Returning cached "+serviceName+" object");
return service;
}
}
return null;
}
addService(newService){
let exists = false;
for (const service of this.services) {
if(service.getName().toUpperCase()==newService.getName().toUpperCase()){
exists = true;
}
}
if(!exists){
this.services.push(newService);
}
}
}

定义服务定位器,其功能是在获取服务时,优先从缓存中获取,若不存在再查询并加入缓存

class ServiceLocator {
static getService(jndiName){
const service = ServiceLocator.cache.getService(jndiName);
if(service != null){
return service;
}
const context = new InitialContext();
const service1 = context.lookup(jndiName);
ServiceLocator.cache.addService(service1);
return service1;
}
}
ServiceLocator.cache = new Cache();

通过服务定位器获取服务后执行

let service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();


链接: https://www.fly63.com/course/27_1289