耦合就是程序之间的依赖程度,确切一点就是上层代码对下层代码的依赖程度,依赖程度越高说明耦合越高,我们的目标是开发松耦合的代码,降低耦合的方法有很多种,使用接口就是解耦合的方案之一
同样实现数据库的CRUD,若不使用接口,当操作的对象或使用的的数据库改变时,需要大量修改客户端的代码,若定义同样的标准,则可以减少依赖程度,这样的标准就是接口
定义所有数据库操作的公共父接口
public interface IDao {
public <T> List<T> query();
public <T> int insert(T t);
public <T> int update(T t);
public int delete(int id);
}
需要使用数据库操作的类定义特有的接口
public interface IStudentDao extends IDao {
}
public interface ITeacherDao extends IDao {
}
为接口定义实现类
public class StudentDaoImpl implements IStudentDao{
private String sql;
@Override
public List<Student> query() {
List<Student> stuList = new ArrayList<Student>();
sql = "SELECT * FROM student";
try {
stuList = DBUtils.selectList(DBUtils.getConnection(), sql, Student.class);
} catch (Exception e) {
e.printStackTrace();
}
return stuList;
}
@Override
public <Student> int insert(Student t) {
sql = "INSERT INTO student(id,sname,age,classid) VALUES(?,?,?,?)";
try {
Connection con = DBUtils.getConnection();
return DBUtils.add(con, sql, t);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 根据对象的id更新对象属性
*/
@Override
public <Student> int update(Student t) {
sql = "UPDATE student SET sname=?,age=?,classid=? WHERE id=?";
try{
Connection con = DBUtils.getConnection();
return DBUtils.edit(con, sql, t);
}catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delete(int id) {
sql = "DELETE FROM student WHERE id=?";
try{
Connection con = DBUtils.getConnection();
return DBUtils.remove(con, sql, id);
}catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
客户端调用时使用父接口指向实现类对象,需求更换时只需要更换实现类就可以了
public class Test {
public static void main(String[] args) {
IDao s = new StudentDaoImpl();
System.out.println(s.delete(166));
}
}