手写一个简单的工厂模式(二)

图中这里仍然是耦合的

 

所以首先在BeanFactory类中新增方法getUserDAO()

    public static UserDAO getUserDAO(){
        UserDAO userDAO = null;
        try {
            Class clazz = Class.forName(env.getProperty("userDAO"));
            //Object obj = clazz.newInstance();
            userDAO = (userDAO)clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return userDAO;
    }

然后修改 UserServiceImpl 类获取userDAO对象的方式,改为 private UserDAO userDAO = BeanFactory.getUserDAO();

package com.baizhiedu.basic;

public class UserServiceImpl implements UserService {
    //private UserDAO userDAO = new UserDAOImpl();

    private UserDAO userDAO = BeanFactory.getUserDAO();

    @Override
    public void register(User user) {
        userDAO.save(user);
    }

    @Override
    public void login(String name, String password) {
        userDAO.queryUserByNameAndPassword(name, password);
    }
}

  

 修改applicationContext.properties文件,新增 userDao = com.baizhiedu.basic.UserDAOImpl

userService = com.baizhiedu.basic.UserServiceImpl
userDAO = com.baizhiedu.basic.UserDAOImpl

  

posted @ 2020-08-29 11:52  尐鱼儿  阅读(275)  评论(0编辑  收藏  举报