6/07/2013
3:03:00 PM 0

Service Locator Pattern

將取得服務的方法進行封裝, 可降低程式碼間的耦合度

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public final class ServiceLocator {

 private static ServiceLocator sl = new ServiceLocator();
 private Context c;
 private Map m;

 private ServiceLocator() {
  try {
   c = new InitialContext();
   m = Collections.synchronizedMap(new HashMap());
  } catch (Exception ex) {
   throw new ExceptionInInitializerError(ex);
  }
 }

 public static ServiceLocator getInstance() {
  return sl;
 }

 public DataSource getDataSource(String name) throws NamingException {
  DataSource ds = null;

  if (m.containsKey(name)) {
   ds = (DataSource) m.get(name);
  } else {
   ds = (DataSource) c.lookup(name);
   m.put(name, ds);
  }

  return ds;
 }
}

0 comments:

Post a Comment