@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"); returnnewService1(); }elseif (jndiName.equalsIgnoreCase("SERVICE2")){ System.out.println("Looking up and creating a new Service2 object"); returnnewService2(); } returnnull; } }
publicclassServiceLocatorPatternDemo { publicstaticvoidmain(String[] args) { Serviceservice= 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