Example 8.34 Implementing Type Checked Service Locator Strategy package corepatterns.apps.psa.util; // imports ... public class ServiceLocator { // singleton's private instance private static ServiceLocator me; static { me = new ServiceLocator(); } private ServiceLocator() {} // returns the Service Locator instance static public ServiceLocator getInstance() { return me; } // Services Constants Inner Class - service objects public class Services { final public static int PROJECT = 0; final public static int RESOURCE = 1; } // Project EJB related constants final static Class PROJECT_CLASS = ProjectHome.class; final static String PROJECT_NAME = "Project"; // Resource EJB related constants final static Class RESOURCE_CLASS = ResourceHome.class; final static String RESOURCE_NAME = "Resource"; // Returns the Class for the required service static private Class getServiceClass(int service){ switch( service ) { case Services.PROJECT: return PROJECT_CLASS; case Services.RESOURCE: return RESOURCE_CLASS; } return null; } // returns the JNDI name for the required service static private String getServiceName(int service){ switch( service ) { case Services.PROJECT: return PROJECT_NAME; case Services.RESOURCE: return RESOURCE_NAME; } return null; } /* gets the EJBHome for the given service using the ** JNDI name and the Class for the EJBHome */ public EJBHome getHome( int s ) throws ServiceLocatorException { EJBHome home = null; try { Context initial = new InitialContext(); // Look up using the service name from // defined constant Object objref = initial.lookup(getServiceName(s)); // Narrow using the EJBHome Class from // defined constant Object obj = PortableRemoteObject.narrow( objref, getServiceClass(s)); home = (EJBHome)obj; } catch( NamingException ex ) { throw new ServiceLocatorException(...); } catch( Exception ex ) { throw new ServiceLocatorException(...); } return home; } }