Service Locator Pattern

Discussions

General J2EE: Service Locator Pattern

  1. Service Locator Pattern (1 messages)

    I am trying to reuse my getConnection() method for getting Connection. Here is a code snippet -

    private Connection getConnection() throws Exception {
            DataSource dsource = null;
            Context ctx = null;
            try {
                Hashtable parms = new Hashtable();
                parms.put(
                    Context.INITIAL_CONTEXT_FACTORY,
                    "com.ibm.ejs.ns.jndi.CNInitialContextFactory");

               ctx = new InitialContext(parms);
                dsource = (DataSource) ctx1.lookup(..<
            } catch (NamingException e) {
    :
    :
            } catch (Exception ex) {
    :
                throw ex;
    :
            } finally {
                try {

                    ctx.close();

                } catch (Exception e) {

                    :
    :

                }
            }

    But I am repeating this code everywhere i need the conncetion. I know about "Service Locator" pattern, but I don't have any EJB's, so my question is -

    How can i use the above code with "Service Locator" pattern. My whole objective is not to make 10 calls for the same stuff and make the code robut.

    May be J2EE Designers can find this question relatively easy. Also, I will greatly appreciate if you reply back with code snippet..

    Thanks a lot
  2. Service Locator Pattern[ Go to top ]

    The Service Locator pattern is not EJB specific. You can use for any kind of managed resource: JDBC connection, JNDI initial context, JMS connections and queues, etc.

    To promote your method to a simple Service Locator, make it a public static method and assign it to a specific class (say "ConnectionFactory"). Or you can jazz it up to do something fancier.