package com.wecloud.dispatch.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 管理存放系统对象
 *
 * @author lixiaozhong
 */
public class ObjectFactory extends AbstractFactory {

	private Map<Class<?>, Class<?>> map = new ConcurrentHashMap<Class<?>, Class<?>>();
	private Map<Class<?>, Map<String, Object>> multipleMap = new ConcurrentHashMap<Class<?>, Map<String, Object>>();
	private Lock lock = new ReentrantLock();

	/**
	 * 注册定义类和实现类的关系<br>
	 *
	 * @param defineClass
	 * @param instanceClass
	 */
	public <T> void register(Class<T> defineClass, Class<? extends T> instanceClass) {
		map.put(defineClass, instanceClass);
	}

	@Override
	public <T> T getObject(Class<T> classType) {
		return getObject(classType, false, false);
	}

	@Override
	public <T> T getObject(Class<T> classType, boolean createNew) {
		return getObject(classType, createNew, false);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getObject(Class<T> classType, boolean createNew, boolean cover) {
		T o = null;
		Class<T> clazz = (Class<T>) map.get(classType);
		if (null != clazz) {
			o = super.getObject(clazz, createNew, cover);
		} else {
			o = super.getObject(classType, createNew, cover);
		}
		return o;
	}

	@SuppressWarnings("unchecked")
	public <T> T getObject(String key, Class<T> classType) {
		Object o = null;
		lock.lock();
		try {
			Map<String, Object> objectMap = multipleMap.get(classType);
			if (null == objectMap) {
				objectMap = new ConcurrentHashMap<String, Object>(16);
				multipleMap.put(classType, objectMap);
			}
			o = objectMap.get(key);
			if (null == o) {
				o = super.createObject(classType);
				if (null != o) {
					objectMap.put(key, o);
				}
			}
		} finally {
			lock.unlock();
		}
		return (T) o;
	}
}
