如何设计DAO类? [英] How to design a DAO class?

查看:108
本文介绍了如何设计DAO类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



方法#1: >将DAO类设计为对象

  class Customer {
// customer class
}

class CustomerDAO {
public void saveCustomer(Customer customer){
// code
}

public Customer getCustomer(int id){
// code
}
}

//客户端代码
class client {
public static void main(String [ ] args){

CustomerDAO customerDAO = new CustomerDAO();
客户客户=新客户();
customerDAO.saveCustomer(customer);
}
}

方法#2: / em> 使用静态方法设计DAO类(又名静态类)

 客户{
//客户类
}

class CustomerDAO {
public static void saveCustomer(Customer customer){
// code
}

public static Customer getCustomer(int id){
// code
}
}

//客户端代码
class client {
public static void main(String [] args){

Customer customer = new Customer();
CustomerDAO.saveCustomer(customer);
}
}

在方法#1中,我必须创建一个对象的所有客户端代码中的DAO类(其他选项是传递DAO的引用)。而在方法#2中,我不必创建对象,静态方法可以设计为没有状态跟踪。



那么哪种方法是最好的设计DAO课程?

解决方案

我建议使用方法#1,但会使用Spring进行依赖注入,而不是直接实例化DAO。



这样,对于单元测试客户端代码,您可以替换模拟DAO,并验证使用适当参数调用正确的DAO。 (Mockito在这里很有用。)



如果使用静态方法,那么单元测试要困难得多,因为静态方法不能被覆盖。 b

What should be the best way to design a DAO class ?

Approach#1: Design DAO class as an object.

class Customer {
//customer class
}

class CustomerDAO {
  public void saveCustomer(Customer customer) {
  //code
  }

  public Customer getCustomer(int id) {
  //code
  }
}

//Client code
class client {
  public static void main(String[] args) {

   CustomerDAO customerDAO = new CustomerDAO();
   Customer customer = new Customer();
   customerDAO.saveCustomer(customer);
  }
}

Approach#2: Design DAO class with static methods (aka static class)

class Customer {
//customer class
}

class CustomerDAO {
  public static void saveCustomer(Customer customer) {
  //code
  }

  public static Customer getCustomer(int id) {
  //code
  }
}

//Client code
class client {
  public static void main(String[] args) {

   Customer customer = new Customer();
   CustomerDAO.saveCustomer(customer);
  }
}

In approach#1, I have to create an object of DAO class in all the client code (other option is to pass the reference of DAO all around). while in approach#2, I do not have to create the object and the static methods can be designed with no state tracking.

So which approach is the best in design of DAO classes ?

解决方案

I would recommend approach #1, but would use Spring for dependency injection rather than instantiating DAOs directly.

This way, for unit testing the client code, you can substitue mock DAOs, and verify that the correct DAOs are invoked with the appropriate arguments. (Mockito is useful here.)

If you use static methods, then unit testing is much more difficult, since static methods cannot be overridden.

这篇关于如何设计DAO类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆