public class Service1 implements Service { @Override public String getName() { return "Service1"; }
@Override public void execute() { System.out.println("Executing Service1"); } }
Service2.java
1 2 3 4 5 6 7 8 9 10 11
public class Service2 implements Service { @Override public String getName() { return "Service2"; }
@Override public void execute() { System.out.println("Executing Service2"); } }
2.3 步骤 3
为 JNDI 查询创建 InitialContext。 InitialContext.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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 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; } }
三、测试
使用 ServiceLocator 来演示服务定位器设计模式。
3.1 编写测试类
ServiceLocatorPatternDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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(); }
}
3.2 执行程序,输出结果
Looking up and creating a new Service1 object Executing Service1 Looking up and creating a new Service2 object Executing Service2 Returning cached Service1 object Executing Service1 Returning cached Service2 object Executing Service2