/* 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 SimpleObjectFactory implements ObjectFactory {
  protected Class classType = null;

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

  public SimpleObjectFactory(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 obj) {
    return obj.isAvailable() && classType.isAssignableFrom(obj.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 SimpleObjectFactory)) return false;
    return classType.equals(((SimpleObjectFactory)obj).classType);
  }

}