初始模式:
dao层接口:
public interface UserDao {
void getUser();
}
dao层实现类:
public class UserDaoImpl implements UserDao {
public void getUser() {
System.out.println("默认获取用户的数据");
}
}
service层接口:
public interface UserService {
void getUser();
}
service层实现类:
public class UserServiceImpl implements UserService {
//程序猿手动创建dao层对象,用来调用dao层方法
private UserDao userDao = new UserDaoImpl();
public void getUser() {
userDao.getUser();
}
}
servlet调用方法时:
UserService userService = new UserServiceImpl();
userServiceImpl.getUser();
需要扩展功能时:
public class UserDaoMysqlImpl implements UserDao{
@Override
public void getUser() {
System.out.println("Mysql获取用户数据!");
}
}
sevice层需要修改代码:
private UserDao userDao = new UserDaoImpl();-->private UserDao userDao = new UserDaoMysqlImpl();
此种方式若在dao层增加功能时,需要程序员修改service层代码,以实现对不同dao层对象的调用,此时,程序主动创建对象,控制权掌握在程序员手上!这样不利于后期的更新维护,违反了开闭性原则.
修改之后:
service层
public class UserServiceImpl implements UserService {
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
public void getUser() {
userDao.getUser();
}
}
servlet调用方法时:
UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoMySqlImpl() );
service.getUser();
==这样添加了set方法之后,巧妙的利用了多态,实现了对控制权的反转,原先由程序来创建的userDao,现在交给了调用者决定创建谁,使得系统的耦合性降低.==
现在当你需要横向扩展你的dao层代码时,不会再影响到service层,这不正是==面向切面编程==的思想吗,spring框架在很多地方都巧妙地实现了控制反转.
本文为学习狂神sping框架有感,附上链接:
https://www.cnblogs.com/hellokuangshen/p/11249253.html