代码之家  ›  专栏  ›  技术社区  ›  Amir Raminfar Hadi Rasouli

如何将数据与业务逻辑分离

  •  8
  • Amir Raminfar Hadi Rasouli  · 技术社区  · 14 年前

    这里是场景,

    假设我有一个这样的用户类:

    public class User{
      private String firstName;
      private String lastName;
    //...
    // setter, getters
    }
    

    然后我有一个这样的类来处理用户评论:

    public class Comments{
      // some fields
      public static loadComments(User user, int count){...}
    }
    

    到目前为止非常基本的东西。不过,我当然想添加一些帮助器,以便更容易地为用户加载注释。所以我可以在用户类中创建一些东西:

    final static int defaultCount = 10;
    ...
    public Comment comments(){
      return Comments.loadComments(this, defaultCount);
    }
    

    我认为这是一种不必传递用户实例的简单方法。但是在这一点上,我很不高兴,因为我已经将用户bean对象与加载注释的业务逻辑耦合起来了。我还保存了用户类中不应该属于该类的默认计数。那么,最好的方法是什么呢?我的目标是将这个对象传递给JSP,以便可以调用JSTL函数。我有个主意创建一个像这样的用户包装器…

    public class UserWrapper{
      private final static defaultCount = 10;
      private final User user;
      public UserWrapper(User user){
        this.user = user;
      }
    
      // should probably cache this but i am not going to show this for simplicity
      public Comments getComments(){return Comments.loadComments(user, 10);}
    }
    

    我希望我是清白的。我不喜欢使用usebean标签,因为它不需要这样做。我希望有一种更清洁的方法来处理类似的事情!任何帮助都将不胜感激!

    编辑 有件事我忘了提。我希望能够在JSTL中使用此代码。这意味着它一定是一个吸气剂。DAO模型是众所周知的,但是当我的前端开发人员需要编写一个脚本或者我需要为他可能需要或者可能不需要的地方加载它时,它没有太多帮助。

    2 回复  |  直到 14 年前
        2
  •  2
  •   Owen    14 年前

    User Comment

    public class UserDAO {
    
         public UserDAO() {
            //maybe setup a Hibernate connection or JDBC connection here
         }
    
         public User getUser(int userId) {
            User user;
            //code to retrieve user from datasource
            return user;
         }
    
         //other methods for update, delete, select, etc
      }
    
      public class CommentsDAO {
         private static int DEFAULT_COUNT = 10;
    
         public CommentsDAO() {
            //maybe setup a Hibernate connection or JDBC connection here
         }
    
         public Collection getCommmentsForUserWithCount(User user, int count) {
            Collection comments = new Set();
            //retrieve comments from datasource limit to count
    
            return comments;
         }
    
         public Collection getCommentsForUser(User user) {
            return getCommentsForUserWithCount(user, DEFAULT_COUNT);
         }
    
         //other methods for update, delete, etc
      }