SSISO Community

시소당

ServiceLocator 패턴 예제

출처 : http://www.oracle.com/technology/sample_code/tech/java/j2ee/vsm12/src/oracle/otnsamples/util/ServiceLocator.java.html

PS ) 깔끔하네요

 

/*
* @author                        : Neelesh
* @Version : 1.0
*
* Development Environment        : Oracle9i JDeveloper
* Name of the File               : ServiceLocator.java
* Creation/Modification History  :
*
* Neelesh  21-Jan-2002      Created
*
*/

package oracle.otnsamples.util;

// Java utility class
import java.util.Hashtable;

// JNDI classes
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * This class is implemented as a singleton class and is a central
 * place for looking up objects in the JNDI tree.
 */
public class ServiceLocator {
 
  // Cache of objects in JNDI tree
  private Hashtable homeCache;
 
  // Initial context
  private InitialContext defaultContext;
 
  // Singleton instance
  private static ServiceLocator serviceLocator = new ServiceLocator();
 
  /**
   * Private constructor which initializes all the tables and the
   * default InitialContext.
   */
  private ServiceLocator() {
    try {
      homeCache = new Hashtable();
      defaultContext = new InitialContext();
    } catch( Exception ex ) {
      System.out.println("Exception in the constructor of ServiceLocator class "+
                         "of given status "+ex.toString());
    }
  }

  /**
   * Method to access the SingleTon instance of the ServiceLocator
   * @return <b>ServiceLocator</b> The instance of this class
   */
  public static ServiceLocator getLocator() {
    return serviceLocator;
  }

  /**
   * Method to return an object in the default JNDI context, with
   * the supplied JNDI name.
   * @param <b>jndiName</b> The JNDI name
   * @returns <b>Object</b> The object in the JNDI tree for this name.
   * @throws <b>UtilityException</b> Exception this method can throw 
   */
  public Object getService( String jndiName )
                throws UtilityException {
    try {
      // If the service is not in the cache,
      if( !homeCache.containsKey( jndiName ) ) {
        // Get the object for the supplied jndi name and put it in the cache
        homeCache.put( jndiName, defaultContext.lookup( jndiName ) );
      }
    } catch( NamingException ex ) {
      throw new UtilityException( "Exception thrown from getService " +
                                  "method of ServiceLocator class of given "+
                                  "status : " + ex.getMessage() );
    } catch( SecurityException ex ) {
      throw new UtilityException( "Exception thrown from from getService " +
                                  "method of ServiceLocator class of given "+
                                  "status : " + ex.getMessage() );
    }
    // Return object from cache
    return homeCache.get( jndiName );
  }
}

1348 view

4.0 stars