服务定位器模式(Service Locator Pattern)用于使用 JNDI 查询定位各种服务。考虑到为某个服务查找 JNDI 的代价很高,服务定位器模式充分利用了缓存技术。在首次请求某个服务时,服务定位器在 JNDI 中查找服务,并缓存该服务对象。当再次请求相同的服务时,服务定位器会在缓存中查找,这样在很大程度上可以提高应用程序的性能。
// 服务接口
public interface Service {
public String getName();
public void execute();
}
// 服务实现
public class Service1 implements Service {
public void execute() {
System.out.println("Executing Service1");
}
@Override
public String getName() {
return "Service1";
}
}
public class Service2 implements Service {
public void execute() {
System.out.println("Executing Service2");
}
@Override
public String getName() {
return "Service2";
}
}
// 初始上下文
public class InitialContext {
public Object lookup(String jndiName) {
if(jndiName.equalsIgnoreCase("SERVICE1")) {
System.out.println("Looking up and creating a new Service1 object");
return new Service1();
} else if (jndiName.equalsIgnoreCase("SERVICE2")) {
System.out.println("Looking up and creating a new Service2 object");
return new Service2();
}
return null;
}
}
// 缓存
public class Cache {
private List services;
public Cache() {
services = new ArrayList();
}
public Service getService(String serviceName) {
for (Service service : services) {
if(service.getName().equalsIgnoreCase(serviceName)) {
System.out.println("Returning cached " + serviceName + " object");
return service;
}
}
return null;
}
public void addService(Service newService) {
boolean exists = false;
for (Service service : services) {
if(service.getName().equalsIgnoreCase(newService.getName())) {
exists = true;
}
}
if(!exists) {
services.add(newService);
}
}
}
// 服务定位器
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache();
}
public static Service getService(String jndiName) {
Service service = cache.getService(jndiName);
if(service != null) {
return service;
}
InitialContext context = new InitialContext();
Service service1 = (Service)context.lookup(jndiName);
cache.addService(service1);
return service1;
}
}
// 使用示例
public class ServiceLocatorPatternDemo {
public static void main(String[] args) {
Service service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
}
}