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; } }
publicclassServiceLocator{ privatestatic Cache cache; static { cache = new Cache(); } publicstatic 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; } }
步骤 6
使用 ServiceLocator 来演示服务定位器设计模式。
1 2 3 4 5 6 7 8 9 10 11 12
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(); } }
步骤 7
执行程序,输出结果:
1 2 3 4 5 6 7 8
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
Copyright 2021 sunfy.top ALL Rights Reserved