Wednesday, November 3, 2010

Factory Pattern Java Code

Factory Pattern: You can learn definition of Factory Pattern from various sources like books, java websites etc. Please look the code below for a working Dyanmic configurable factory java code.

How to use: Make a factory.properties file and put your key and class names as key value pair in this file and you are ready to use this factory.

package org.paandav.factory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class DynamicFactory {
 private static final String FACTORY_FILE_NAME = "factory.properties";
 private static final DynamicFactory factory = new DynamicFactory();
 private static Map<String, String> keyClassMap = null;

 public static DynamicFactory getInstance() throws DynamicFactoryException {
  if (keyClassMap == null) {
   synchronized (DynamicFactory.class) {
    if (keyClassMap == null) {
     initialize();
    }
   }
  }
  return factory;
 }

 @SuppressWarnings("unchecked")
 public Object getObject(String key) throws DynamicFactoryException {
  String clsName = keyClassMap.get(key);
  Object obj = null;
  if (null == clsName || "".equals(clsName.trim())) {
   throw new DynamicFactoryException("Class for key " + key
     + " not found");
  }
  try {
   Class cls = Class.forName(clsName);
   obj = cls.newInstance();
  } catch (Exception cnf) {
   throw new DynamicFactoryException(clsName + " can not instatitate.");
  }

  return obj;
 }
 private static void initialize() throws DynamicFactoryException {
  try {
   File pfile = new File(FACTORY_FILE_NAME);
   Properties pro = null;
   InputStream is = null;

   if (pfile.exists()) {
    pro = new Properties();
    is = new FileInputStream(pfile);
    pro.load(is);
    if (pro.size() > 0) {
     keyClassMap = new HashMap<String, String>();
     Set<String> keys = pro.stringPropertyNames();
     for (String key : keys) {
      if (null != pro.getProperty(key)
        && !"".equals(pro.getProperty(key).trim())) {
       keyClassMap.put(key, pro.getProperty(key));
      }
     }
    }
   }
  } catch (Throwable th) {
   keyClassMap = null;
   throw new DynamicFactoryException(th.getMessage());
  }
 }
}



package org.paandav.factory;
public class DynamicFactoryException extends Exception {
 private static final long serialVersionUID = 1L;
 public DynamicFactoryException() {
  super();
 }

 public DynamicFactoryException(String msg) {
  super(msg);
 }

}

No comments:

Post a Comment