/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.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 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);
    }

}

