ObjectFactory采用单列模式设置工厂模式

package util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

// 采用单例模式来设计工厂
public class ObjectFactory {
	// 定义一个集合用于存储对象的名字和实例
	private static Map factory;

	private static ObjectFactory instance = null;

	private static Properties props = null;
	
	public static Properties getProps() {
		return props;
	}

	private ObjectFactory() {
		
	}
	
	static {
		// 初始化模型工厂
		factory = new HashMap();

		// 初始化对象工厂映射文件objectName
		props = new Properties();
		try {
			// 通过当前类加载器去读取classpath下的文件流
			InputStream is = ObjectFactory.class
					.getResourceAsStream("/object.properties");
			props.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 根据对象名称获得工厂内的实例(必须要检查你需要的对象在工厂中有没有)
	// 当你请求该对象时,才临时初始化返回
	public static Object getObject(String objectName) {
		if (instance == null)
			instance = new ObjectFactory();
		Object object=null;
		try {
			object = factory.get(objectName);
			if (object == null) {
				// 如果为null,证明这个对象在工厂中尚未初始化,实例化它并把它放入工厂中
				object = Class.forName(props.getProperty(objectName))
						.newInstance();
				factory.put(objectName, object);
				System.out.println("init "+objectName);
			} else {
				System.out.println("return "+objectName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return object;
	}

}

读取的配置文件object.properties

transaction=transaction.impl.MyBatisTransactionManagerImpl
userDao=daoImpl.UserDaoImpl
companyDao=daoImpl.CompanyDaoImpl
productDao=daoImpl.ProductDaoImpl
userService=service.impl.UserServiceImpl
productService=service.impl.ProductServiceImpl
lendingperiodService=service.impl.LendingPeriodServiceImpl
companyService=service.impl.CompanyServiceImpl
productTypeService=service.impl.ProductTypeServiceImpl
newsService=service.impl.NewsServiceImpl
applyService=service.impl.ApplyServiceImpl

你可能感兴趣的:(Java)