Factory.java :  » UnTagged » dailylife » com » dailystudio » factory » Android Open Source

Android Open Source » UnTagged » dailylife 
dailylife » com » dailystudio » factory » Factory.java
package com.dailystudio.factory;

import java.util.Map;

import com.dailystudio.development.Logger;

import android.content.Context;

public abstract class Factory<T, P> {
  
    private static Map<Class<?>,Object> sInstanceMap =
        new java.util.HashMap<Class<?>,Object>();
    
    protected Factory() {
      initMembers();
    }
    
    protected void initMembers() {
    }

    public static synchronized <E> E getInstance(Class<E> clazz) {
        E instance = clazz.cast(sInstanceMap.get(clazz));
        if (instance != null) {
            return instance;
        }
        
        try {
            instance = clazz.cast(clazz.newInstance());
        } catch (InstantiationException exc) {
            throw new IllegalArgumentException(exc);
        } catch (IllegalAccessException exc) {
            throw new IllegalArgumentException(exc);
        } catch (ClassCastException exc) {
            throw new IllegalArgumentException(exc);
        }
        
        sInstanceMap.put(clazz, instance);
        
        return instance;
    }
    
    public T createObject(P params) {
      return newObject(params);
    }
    
    abstract protected T newObject(P params);
    
  private static Context sContext = null;
  
  public synchronized static void bindContext(Context context) {
    sContext = context;
  }
  
  public synchronized static void unbindContext() {
    sContext = null;
  }
  
    public synchronized static Context getContext() {
      if (sContext == null) {
        Logger.warnning("NULL context, please call bindContext() firstly.");
      }
      return sContext;
    }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.