如图所示为一个简单的IOC模型
一、感受IOC
dao下
public interface UserDao {
public void getUser();
}
public class UserDaoImpl implements UserDao {
@Override
public void getUser() {
System.out.println("获取用户");
}
}
service下
public interface UserService {
public void getUser();
}
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public void getUser() {
userDao.getUser();
}
}
test下
public class MyTest {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
思考一个问题,现在只要一个dao需要,那如果又多出来两个数据库信息获取呢?
public class UserDaoMysqlImpl implements UserDao {
@Override
public void getUser() {
System.out.println("从musql获取数据");
}
}
public class UserDaoOracleImpl implements UserDao {
@Override
public void getUser() {
System.out.println("从oracle中获取数据");
}
}
难道要对service每次修改,然后在test中挨个实现吗? 不行,这不现实 那么应该怎么做呢? 可以这样
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
public class MyTest {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserDaoMysqlImpl userDaoMysql = new UserDaoMysqlImpl();
userService.setUserDao(userDaoMysql);
userService.getUser();
System.out.println("----------------");
UserDaoOracleImpl userDaoOracle = new UserDaoOracleImpl();
userService.setUserDao(userDaoOracle);
userService.getUser();
}
}
至此,对IOC有了大致的感受
|