工厂类解耦

2020-01-20  本文已影响0人  茶酒qqq

手动实现工厂类:

public class BeanFactory {
    private static Properties properties;
    private static Map<String , Object> beans;
    static {
        try {
            //实例化对象
            properties = new Properties();
            //获取properties文件流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(in);

            beans=new HashMap<String, Object>();
            Enumeration keys=properties.keys();
            while(keys.hasMoreElements()){
                //取出每个key
                String key=keys.nextElement().toString();
                //根据key获取value
                String keyPath=properties.getProperty(key);
                System.out.println(keyPath);
                //根据keyPath创建反射对象
                Object value=Class.forName(keyPath).newInstance();
                //放入map
                beans.put(key,value);
            }
        }catch (Exception e){
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
    }

    public static Object getBean(String beanName){
        return beans.get(beanName);
    }

}

bean.properties

accountService=com.chajiu.service.AccountServicelmpl
accountDao=com.chajiu.dao.AccountDAOlmpl

创建对象:

IAccountService service = (IAccountService) BeanFactory.getBean("accountService");
上一篇 下一篇

猜你喜欢

热点阅读