回调的妙用

阅读更多

 

     回调一般在java应用中,于window编程比较多,本人在这方面经验比较少,对回调的应用经验几乎是空白,因此对JAVA的回调技术没什么了解。

     后来也就是在使用hibernate的时候,应用了spring包装的hibnerte 的API类HibernateDaoSupport的时候,在分页查询,应用了Criteria的动态查询,HibernateTemplate支持得不是很好,就用了回调的技术

    

java 代码
  1. public PaginationSupport findPageByCriteria(   
  2.             final DetachedCriteria detachedCriteria, final int page,   
  3.             final int pageSize) {   
  4.         return (PaginationSupport) getHibernateTemplate().execute(   
  5.                 new HibernateCallback() {   
  6.                     public Object doInHibernate(Session session)   
  7.                             throws HibernateException {   
  8.                         Criteria criteria = detachedCriteria   
  9.                                 .getExecutableCriteria(session);   
  10.                         int totalCount = ((Integer) criteria.setProjection(   
  11.                                 Projections.rowCount()).uniqueResult())   
  12.                                 .intValue();   
  13.                         criteria.setProjection(null);   
  14.                         List items = criteria.setFirstResult(page)   
  15.                                 .setMaxResults(pageSize).list();   
  16.                         PaginationSupport ps = new PaginationSupport(items,   
  17.                                 totalCount, pageSize, page);   
  18.                         return ps;   
  19.                     }   
  20.                 }, true);   
  21.     }  

 

         后来看到有关回调技术的说法:

        当通常大家说的回调函数一般就是按照别人的定好的接口规范写的,等待别人调用的函数,在C语言中,回调函数通常通过函数指针来传递;在Java中,通常就是编写另外一个类或类库的人规定一个接口,然后你来实现这个接口,然后把这个实现类的一个对象作为参数传给别人的程序,别人的程序必要时就会通过那个接口来调用你编写的函数。

        最近在研究jive论坛,在搜索的时候它使用了Ietorator,其中就是使用了回调的技术,忽然眼前一亮,至此,才看到回调的妙用。

        看片断,构造函数:

java 代码
  1. public DatabaseObjectIterator(int type, long [] elements,   
  2.            final Object extraObject)   
  3.    {   
  4.        this.elements = elements;   
  5.   
  6.        // Load the appropriate proxy factory depending on the type of object   
  7.        // that we're iterating through.   
  8.        switch (type) {   
  9.            // FORUM   
  10.            case JiveGlobals.FORUM:   
  11.                // Create an objectFactory to load forums.   
  12.                this.objectFactory = new DatabaseObjectFactory() {   
  13.                    ForumFactory factory = (ForumFactory)extraObject;   
  14.   
  15.                    public Object loadObject(long id) {   
  16.                        try {   
  17.                            Forum forum = factory.getForum(id);   
  18.                            return forum;   
  19.                        }   
  20.                        catch (ForumNotFoundException mnfe) { }   
  21.                        catch (UnauthorizedException ue) { }   
  22.                        return null;   
  23.                    }   
  24.                };   
  25.                break;  

      

  1. //THREAD   
  2.            case JiveGlobals.THREAD:   
  3.                // Create an objectFactory to load threads. There are two   
  4.                // possibilities -- the first is that extraObject is a   
  5.                // Forum that we can directly load threads from. The   
  6.                // second is that extraObject is a DbForumFactory. The latter   
  7.                // case can occur when we need to iterate through a set of   
  8.                // threads that come from multiple different forums.   
  9.                if (extraObject instanceof Forum) {   
  10.                    this.objectFactory = new DatabaseObjectFactory() {   
  11.                        Forum forum = (Forum)extraObject;   
  12.   
  13.                        public Object loadObject(long id) {   
  14.                            try {   
  15.                                ForumThread thread = forum.getThread(id);   
  16.                                return thread;   
  17.                            }   
  18.                            catch (ForumThreadNotFoundException tnfe) { }   
  19.                            return null;   
  20.                        }   
  21.                    };   
  22.                }   
  23.                else {   
  24.                    this.objectFactory = new DatabaseObjectFactory() {   
  25.                        DbForumFactory factory = (DbForumFactory)extraObject;   
  26.   
  27.                        public Object loadObject(long id) {   
  28.                            try {   
  29.                                return factory.cacheManager.threadCache.get(id);   
  30.                            }   
  31.                            catch (ForumThreadNotFoundException mnfe) { }   
  32.                            return null;   
  33.                        }   
  34.                    };   
  35.                }   
  36.                break;  

 

  1. //MESSAGE   
  2.            case JiveGlobals.MESSAGE:   
  3.                // Create an objectFactory to load messages. There are two   
  4.                // possibilities -- the first is that extraObject is a   
  5.                // ForumThread that we can directly load messages from. The   
  6.                // second is that extraObject is a DbForumFactory. The latter   
  7.                // case can occur when we need to iterate through a set of   
  8.                // messages that come from multiple different threads.   
  9.                if (extraObject instanceof ForumThread) {   
  10.                    this.objectFactory = new DatabaseObjectFactory() {   
  11.                        ForumThread thread = (ForumThread)extraObject;   
  12.   
  13.                        public Object loadObject(long id) {   
  14.                            try {   
  15.                                ForumMessage message = thread.getMessage(id);   
  16.                                return message;   
  17.                            }   
  18.                            catch (ForumMessageNotFoundException mnfe) { }   
  19.                            return null;   
  20.                        }   
  21.                    };   
  22.                }   
  23.                else {   
  24.                    this.objectFactory = new DatabaseObjectFactory() {   
  25.                        DbForumFactory factory = (DbForumFactory)extraObject;   
  26.   
  27.                        public Object loadObject(long id) {   
  28.                            try {   
  29.                                ForumMessage message =   
  30.                                        factory.cacheManager.messageCache.get(id);   
  31.                                // Now, get the message from its thread so that   
  32.                                // filters are applied to the message.   
  33.                                message = message.getForumThread().getMessage(id);   
  34.                                return message;   
  35.                            }   
  36.                            catch (ForumMessageNotFoundException mnfe) { }   
  37.                            return null;   
  38.                        }   
  39.                    };   
  40.                }   
  41.                break;  

 

  1. //USER   
  2.           case JiveGlobals.USER:   
  3.               // Create an objectFactory to load users.   
  4.               this.objectFactory = new DatabaseObjectFactory() {   
  5.                   UserManager userManager = (UserManager)extraObject;   
  6.   
  7.                   public Object loadObject(long id) {   
  8.                       try {   
  9.                           User user = userManager.getUser(id);   
  10.                           return user;   
  11.                       }   
  12.                       catch (UserNotFoundException unfe) { }   
  13.                       return null;   
  14.                   }   
  15.               };   
  16.               break;   
  17.           //GROUP   
  18.           case JiveGlobals.GROUP:   
  19.               // Create an objectFactory to load groups.   
  20.               this.objectFactory = new DatabaseObjectFactory() {   
  21.                   GroupManager groupManager = (GroupManager)extraObject;   
  22.   
  23.                   public Object loadObject(long id) {   
  24.                       try {   
  25.                           Group group = groupManager.getGroup(id);   
  26.                           return group;   
  27.                       }   
  28.                       catch (GroupNotFoundException gnfe) { }   
  29.                       return null;   
  30.                   }   
  31.               };   
  32.               break;   
  33.           // Otherwise, an invalid value was passed in so throw an exception.   
  34.           default:   
  35.               throw new IllegalArgumentException("Illegal type specified");   
  36.       }   
  37.   }  

定义回调的方法的接口类:

 

 

  1. interface DatabaseObjectFactory {   
  2.   
  3.     /**  
  4.      * Returns the object associated with id or null if the  
  5.      * object could not be loaded.  
  6.      *  
  7.      * @param id the id of the object to load.  
  8.      * @return the object specified by id or null if it could not  
  9.      *      be loaded.  
  10.      */  
  11.     public Object loadObject(long id);   
  12. }  

 

对接口方法的调用

 

java 代码
  1. public Object getNextElement() {   
  2.         while (currentIndex+1 < elements.length) {   
  3.             currentIndex++;   
  4.             Object element = objectFactory.loadObject(elements[currentIndex]);   
  5.             if (element != null) {   
  6.                 return element;   
  7.             }   
  8.         }   
  9.         return null;   
  10.     }  

 

 继续......

你可能感兴趣的:(Hibernate,thread,Spring,编程,DAO)