IOC理论推理
一、推理结构图
1、DAO层接口
package com.li.dao;
public interface UserDao {
void getUser();
}
2、DAO层实现类
在这里插入代package com.li.dao;
/**
* @Description:
* @Author: lizq
**/
public class UserDaoImp implements UserDao{
public void getUser() {
System.out.println("默认获取用户的数据");
}
}码片
package com.li.dao;
/**
* @Description:
* @Author: lizq
**/
public class UserDaoMysqlImp implements UserDao{
public void getUser() {
System.out.println("获取mysql数据~~~");
}
}
3.Service中的接口
package com.li.service;
public interface UserService {
public void getUser();
}
4.Service中实现类
package com.li.service;
import com.li.dao.UserDao;
/**
* @Description:
* @Author: lizq
**/
public class UserServiceImp implements UserService{
// private UserDao userDao = new UserDaoMysqlImp();
private UserDao userDao;
//通过用户选择
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void getUser() {
userDao.getUser();
}
}
5、测试类
import com.li.dao.UserDao;
import com.li.dao.UserDaoImp;
import com.li.service.UserService;
import com.li.service.UserServiceImp;
/**
* @Description:
* @Author: lizq
**/
public class Mytest {
public static void main(String[] args) {
// 缺点:如果dao层实现的UserDao的类有很多,每次调用都得修改类,麻烦
// UserService userService = new UserServiceImp();
UserServiceImp u = new UserServiceImp();
//被动接收对象,用户输入控制权在用户,耦合性降低
u.setUserDao(new UserDaoImp());
u.getUser();
}
}
总结:
这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低-,可以更加专注的在业 务的实现上!这是IOC的原型!