使用工厂模式,处理代码解耦

梦想与她 提交于 2019-12-04 20:51:32

//一般需要两个条件: 1、设置配置文件bean.properties

  //                               2、使用反射机制,获取代理对象的实现类

//配置文件bean.properties(注意不要加“;”号)

accountDao=com.hope.dao.impl.AccountDaoImplaccountService=com.hope.service.impl.AccountServiceImpl
package com.hope.factory;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * @author newcityman * @date 2019/11/18 - 14:44 * 第一个:需要一个配置文件来配置我们的service和dao * 第二个:通过读取配置文件中配置的内容,反射创建对象 */public class BeanFactory {    //定义一个properties对象    public static Properties props;    static {        try {            //定义一个properties对象            props = new Properties();            //获取properties文件的流对象            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");            props.load(in);        } catch (IOException e) {            throw new ExceptionInInitializerError("初始化propteies失败");        }    }    /**     * 根据bean的名称获取bean对象     *     * @param beanName     * @return     */    public static Object getBean(String beanName) {        Object bean=null;        try {            String beanPath = props.getProperty(beanName);            bean = Class.forName(beanPath).newInstance();        } catch (Exception e) {            e.printStackTrace();        }        return bean;    }}
package com.hope.ui;import com.hope.factory.BeanFactory;import com.hope.service.IAccountService;/** * @author newcityman * @date 2019/11/18 - 14:23 */public class Client {    public static void main(String[] args) {//        IAccountService accountService= new accountServiceImpl();        IAccountService accountService=(IAccountService)BeanFactory.getBean("accountService");        accountService.findAll();    }}
 
 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!