@Override public String getName(){ return"Service2"; } }
3. 为 JNDI 查询创建 InitialContext
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassInitialContext { public Object lookup(String jndiName){ if(jndiName.equalsIgnoreCase("SERVICE1")){ System.out.println("Looking up and creating a new Service1 object"); returnnew Service1(); }elseif (jndiName.equalsIgnoreCase("SERVICE2")){ System.out.println("Looking up and creating a new Service2 object"); returnnew Service2(); } returnnull; } }
InitialContext context = new InitialContext(); Service service1 = (Service)context.lookup(jndiName); cache.addService(service1); return service1; } }
6. 使用 ServiceLocator 来演示服务定位器设计模式
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassServiceLocatorPatternDemo { publicstaticvoidmain(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(); } }
编译运行以上 Java 范例,输出结果如下
1 2 3 4 5 6 7 8 9 10
$ javac -d . src/main/cn/twle/gof/ServiceLocatorPatternDemo.java $ java cn.twle.gof.ServiceLocatorPatternDemo 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