package jp.agentec.abook.abv.bl.logic;

import java.util.concurrent.ConcurrentHashMap;

import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.nw.NetworkAdapter;
import jp.agentec.abook.abv.bl.data.ABVDataCache;

/**
 * LogicをSingletonにするためのキャッシュとインスタンスの返却を行う
 */
public abstract class AbstractLogic {
	protected ABVDataCache cache = ABVDataCache.getInstance();
	protected NetworkAdapter networkAdapter = ABVEnvironment.getInstance().networkAdapter;
	protected ABVEnvironment env = ABVEnvironment.getInstance();
	
	@SuppressWarnings("rawtypes")
	private static ConcurrentHashMap<Class, AbstractLogic> daoMap = new ConcurrentHashMap<Class, AbstractLogic>();
	
	@SuppressWarnings("unchecked")
	public static <T extends AbstractLogic> T getLogic(Class<T> clazz) {
		T instance;
		if (daoMap.containsKey(clazz)) {
			instance = (T) daoMap.get(clazz);
		}
		else {
//			synchronized (daoMap) { // パフォーマンスを考慮し、排他制御をしない。最悪２重に作られても各Logicは状態を持たないため影響はなく、参照がなくなったLogicはgc対象となる。
//				if (daoMap.containsKey(clazz)) {
//					instance = (T) daoMap.get(clazz);
//				}
//				else {
					try {
                        //noinspection ClassNewInstance
                        instance = clazz.newInstance();
						daoMap.put(clazz, instance);
					} catch (InstantiationException e) {
						throw new RuntimeException(e);
					} catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
//				}
//			}
		}
		return instance;
	}
	
}
