/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.org
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.pool;

/**
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class ObjectFactorySupport implements ObjectFactory {
  protected Class classType = null;

  public ObjectFactorySupport(Class classType) throws Exception {
    setObjectClass(classType);
  }

  public ObjectFactorySupport(String className) throws Exception {
    Class claz = Thread.currentThread().getContextClassLoader().loadClass(className);
    setObjectClass(claz);
  }

  public Class getObjectClass() {
    return classType;
  }

  public PoolableObject makeObject() throws Exception {
    return (PoolableObject)classType.newInstance();
  }

  /**
   * destroy a poolabled object
   * @param object
   */
  public void destroyObject(PoolableObject object) throws Exception {
//    object = null;
  }

  public boolean validateObject(PoolableObject object) {
    return classType.isAssignableFrom(object.getClass());
  }

  private void setObjectClass(Class classType) throws Exception {
    if(!validateClassType(classType)){
      throw new Exception("class " + classType.getName() + " not derived from " + PoolableObject.class.getName());
    }
    this.classType = classType;
  }
  /**
   * validate the classType is instanceof Poolable object
   * @param classType
   * @return
   */
  private boolean validateClassType(Class classType) {
    if(PoolableObject.class.isAssignableFrom(classType)) {
      return true;
    }
    return false;
  }

  public int hashCode() {
    return classType.hashCode();
  }

  public boolean equals(Object obj) {
    if(!(obj instanceof ObjectFactorySupport)) return false;
    return classType.equals(((ObjectFactorySupport)obj).classType);
  }

}
