论基于数据访问的集合类(Data Access Based Collection)和领域事件(Domain Event)模式 .

来源:互联网 发布:黑客 数据库 股民 编辑:程序博客网 时间:2024/06/07 22:15
 在正式展开之前,有一些概念要先做一个界定。首先:领域模型是指系统应对的领域中所有逻辑的一个抽象,本质上它是领域中各种对象和概念以及它们之间关系的集合。你可以用自然语言描述它,也可以用UML来描述,或者是代码去描述。特别地,当我们使用面向对象建模技术来实现这个领域模型时,我们可以把这个实现出来的模型称之为对象模型。我们可以认为领域模型是一个概念模型,是分析阶段的产物。

  让精心构建的对象模型高效地工作有很多底层的技术问题需要解决,其中如何满足领域对象的业务方法在计算过程中对数据的需求是一个普遍存在的问题(实际上,在实际应用中,我们会遇到更为复杂的情况,不只是有数据的需求,还可能出现对应用层面发生依赖)。对于这一问题,目前有两种模型可供借鉴,那就是基于数据访问的集合类和领域事件模式。


基于数据访问的集合类(Data Access Based Collection)


  基于数据访问的集合类是我在开发oobbs系统时设计的一种模式。这一模式通过一个抽象的接口来代表某一对象依赖的一组集合。当这一对象实例化时,一个基于数据访问的集合实现类会注入到这个对象中,所有通过这一集合进行的操作,比如遍历,增删元素等都是被实现类转化成数据访问操作。基于数据访问的集合类很像是一个缩水版的Repository。还是以Forum的public List<Thread> getThreads()方法为例,我们认为getThreads是Forum的一个典型的业务方法,但是由于一个Forum拥有众多的Thread,这使得我们根本不容许一次将这个集合全部加载出来。即使是在hibernate这类提供了lazy和extra lazy加载机制ORM工具里,也无法避免当我们直得去迭代这一集合时,它们会被一次性全部加载。而另一方面,实际的应用请求也不会一次请求所有的Thread,更常见的情况是以分页的形式,一小批次一小批次地请求。因此基于数据访问的集合模式使用一个集合接口做为一个占位符,并声明了一些基本的集合操作:比如返回某一区间内的子集(为分页而服务)和add,remove等操作,而实现类里,这些方法是以数据访问的方式实现的。下面是集合的接口定义。它看起来很像一个普通的集合。
view plaincopy to clipboardprint?
  1. package oobbs.domainmodel;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  * The collection interface represents a set of objects, it's like the 
  8.  * java.util.Collection, however, there no real objects in this collection, it 
  9.  * only looks like a collection, its method's implementation is database access 
  10.  * operation! see <code>oobbs.infrastructure.persistence.AbstractHibernateCollection</code>  
  11.  * @author laurence.geng 
  12.  */  
  13. public interface Collection<Entity, PK extends Serializable, Owner> {  
  14.     void setOwner(Owner owner);  
  15.   
  16.     void setOwnerName(String ownerName);  
  17.   
  18.     /** 
  19.      * Adds an object. This method will persist entity to database directly! 
  20.      * @param e an entity instance. * @return the pK the generated primary key 
  21.      * after insert into database. 
  22.      */  
  23.     PK add(Entity e);  
  24.   
  25.     void addAll(java.util.Collection<Entity> c);  
  26.   
  27.     /** 
  28.      * Removes the entity. This method will remove this entity from database 
  29.      * directly. 
  30.      */  
  31.     void remove(Entity e);  
  32.   
  33.     void removeAll(java.util.Collection<Entity> c);  
  34.   
  35.     boolean contains(Entity o);  
  36.   
  37.     boolean isEmpty();  
  38.   
  39.     int size();  
  40.   
  41.     /** 
  42.      * The most important method. It returns a subset of the whole collection. 
  43.      * the returned subset is fetched from database by sql, hql or other data 
  44.      * access way, The Collection itself never load all elements once time! 
  45.      */  
  46.     List<Entity> toList(int startIndex, int offset);  
  47.   
  48.     void flush();  
  49. }  

  下面则是基本于hibernate的集合接口实现类。它实现了所有的基本的操作。在Forum类中就会这样一个字段以及相应的getter和setter:

view plaincopy to clipboardprint?
  1. @Transient  
  2. private Collection<Thread, Long, Forum> forumThreads;  
  3.   
  4. @Autowired  
  5. /** 
  6.  * Sets ForumThreadCollection.  
  7.  * ForumThreadCollection is injected by this setter. When a collection instance injected, set this forum to its forum!  
  8.  */  
  9. public void setForumThreads(@Qualifier("forumThreads") Collection<Thread, Long, Forum> forumThreads) {  
  10.     this.forumThreads = forumThreads;  
  11.     this.forumThreads.setOwner(this);  
  12.     this.forumThreads.setOwnerName("forum");  
  13. }  
  14.   
  15. /** 
  16.  *  Gets this forum's thread collection. 
  17.  */  
  18. public Collection<Thread, Long, Forum> getForumThreads() {  
  19.     return forumThreads;  
  20. }  

  其中注入的forumThreads对象是一个名为ForumThreadHibernateCollection的类,它继承了AbstractHibernateCollection类,因为没有特殊的需要,没有重写任何方法。而下面展示的是service中对这集合的一次使用:

view plaincopy to clipboardprint?
  1. List<Thread> threads = forum.getForumThreads().toList(startThreadIndex,threadTotal);  

  我们来分析一下Domain Collection这一模式的优劣。我认为它最大的优点在于它能够以一个字段的形式存在于单端关联对象中,这使得单端对象的定义饱满,完成符合并体现了一对多双向关联中双方依赖关系。这一点是使用hiberate映射无法实现的,因为我们不能在Forum中映射@OneToMany(mappedBy="forum") private Set<Thread> threads;

  但是它的缺点也是非常明显并且似乎是无法克服的,那就是它只能用来表示直接关联的集合,如果单端对象想通过这一集合进一步遍历元素中更深层次的二级,三级集合时,domain collection就显得力不从心了。比方说:在论坛的首页上往往会罗列出各个Forum的一些基本信息,其中之一就是该Forum有多少帖子(Post),相应的,Forum对象会有这样一个方法public Long getPostCount();很显然,Post是Forum的二级集合,一个Forum需要先得到它的Thread集合,再从每个Thread中得到Post集合。我们可以为了这一方法再提供一个ForumPostHibernateCollcetion用来代表一个Forum的所有Post的集合,但是这个集合已经和模型的定义发生了偏离,因为并没有从Forum到Post的直接关联。而更加普遍的问题的是:我们会常常遇到某一个单端实体从它直接依赖的对象开始进行深度地导航(体现在SQL上就是对多个表的join操作),这时候我们不能为每一种导航而创建一个从出发点到结束点的domain collection。在这种情况下,获取数据必须通过另外一种方式进行了,那就是Domain Event模式。


领域事件(Domain Event)

  Domain Event模式最初由udi dahan提出,发表在自己的博客上:http://www.udidahan.com/2009/06/14/domain-events-salvation/这一模式得到广泛的认可。它所要应对的正是将领域对象从对repository或service的依赖中解脱出来,避免让领域对象对这些设施产生直接依赖。它的做法就是当领域对象的业务方法需要依赖到这些对象时就发出一个事件,这个事件会被相应的对象监听到并做出处理。在我的oobbs系统中,我对这一模式做了一些改进,主要是消除静态方法和规范事件模型。在我的方案中,这一机制由这样几个角色:DomainEventDispatcher,DomainEvent和DomainEventListener.

  DomainEventDispatcher会以字段的形式存在于领域对象中,负责在业务方法中dispatch领域事件。下面是所有Dispatcher的基类:

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. /** 
  7.  * The DomainEventDispatcher take charge of listener registration and dispatch 
  8.  * domain event to corresponding listener to handle. Usually, one dispatch per 
  9.  * domain object. 
  10.  */  
  11. public class DomainEventDispatcher {  
  12.     /** The listener map. all registered listeners are stored in this map. */  
  13.     protected Map<String, DomainObejctListener> listeners = new HashMap<String, DomainObejctListener>();  
  14.   
  15.     /** * Adds a listener. * * @param listener the listener */  
  16.     public void addListener(DomainObejctListener listener) {  
  17.         listeners.put(listener.getName(), listener);  
  18.     }  
  19.   
  20.     /** * Removes all listeners. */  
  21.     public void removeAllListeners() {  
  22.         listeners.clear();  
  23.     }  
  24. }  

一般来说一个领域对象会有一个对应的event dispatcher,这个dispatcher会有一组重载的dispatch方法,用于分发不同的领域事件。下面是oobbs中Forum对象的event dispatcher.

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel.forum;  
  2.   
  3. import oobbs.Constants;  
  4. import oobbs.domainmodel.DomainEventDispatcher;  
  5. import oobbs.domainmodel.ResultCollector;  
  6.   
  7. /** 
  8.  * * The ForumEventDispatcher dispatch all events which about Forum object. * @author 
  9.  * laurence.geng 
  10.  */  
  11. public class ForumEventDispatcher extends DomainEventDispatcher {  
  12.     public void dispatch(GetForumThreadEvent event, ResultCollector result) {  
  13.         ForumListener forumListener = (ForumListener) listeners.get(Constants.FORUM_REPO_AS_FORUM_LISTENER);  
  14.         forumListener.handleGetForumThreadEvent(event, result);  
  15.     }  
  16.   
  17.     public void dispatch(GetForumPostCountEvent event, ResultCollector result) {  
  18.         ForumListener forumListener = (ForumListener) listeners.get(Constants.FORUM_REPO_AS_FORUM_LISTENER);  
  19.         forumListener.handleGetFroumPostCountEvent(event, result);  
  20.     }  
  21.   
  22.     public void dispatch(GetForumThreadCountEvent event, ResultCollector result) {  
  23.         ForumListener forumListener = (ForumListener) listeners.get(Constants.FORUM_REPO_AS_FORUM_LISTENER);  
  24.         forumListener.handleGetForumThreadCountEvent(event, result);  
  25.     }  
  26. }  

系统中会有很多的domain event,下面是所有领域事件的基类:

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel;  
  2.   
  3. /** 
  4.  * The supper class of all domain events. all events should provide event 
  5.  * source, the domain object which fired this event. 
  6.  */  
  7. public class DomainEvent {  
  8.     /** The event source, the domain object which fired this event. */  
  9.     protected Object source;  
  10.   
  11.     public DomainEvent(Object source) {  
  12.         super();  
  13.         this.source = source;  
  14.     }  
  15.   
  16.     /** * Gets the event source. * * @return the event source */  
  17.     public Object getSource() {  
  18.         return source;  
  19.     }  
  20. }  

下面就是刚才提到的例子中返回Forum某一部分(分页)Thread的事件,在这个事件中我们看到一个事件可以携带一些参数,供listener使用:

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel.forum;  
  2.   
  3. import oobbs.domainmodel.DomainEvent;  
  4.   
  5. /**  
  6.  * The Event that forum request to get its threads. 
  7.  * @author laurence.geng  
  8.  */  
  9. public class GetForumThreadEvent extends DomainEvent {  
  10.     /** The start index of request thread. */  
  11.     private int startIndex;  
  12.     /** The count of request thread. */  
  13.     private int count;  
  14.   
  15.     public GetForumThreadEvent(Forum source, int startIndex, int count) {  
  16.         super(source);  
  17.         this.startIndex = startIndex;  
  18.         this.count = count;  
  19.     }  
  20.   
  21.     public int getStartIndex() {  
  22.         return startIndex;  
  23.     }  
  24.   
  25.     public int getCount() {  
  26.         return count;  
  27.     }  
  28. }  

而下面就是我们所有listener的基类:

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel;  
  2.   
  3. /** 
  4.  * The super class of all domain object listeners. it handles events from 
  5.  * domain objects. Each listener has to provide a name as key for registering 
  6.  * itself to dispatcher.  
  7.  * @see DomainObejctEvent  
  8.  * @author laurence.geng 
  9.  */  
  10. public interface DomainObejctListener {  
  11.     /** * Gets the name. * * @return the name */  
  12.     public String getName();  
  13. }  

下面是Forum的listenerr接口,这个接口会有很多handle方法,代码只展示了一个。

view plaincopy to clipboardprint?
  1. package oobbs.domainmodel.forum;  
  2.   
  3. import oobbs.domainmodel.DomainObejctListener;  
  4. import oobbs.domainmodel.ResultCollector;  
  5.   
  6. /** 
  7.  * * The forum listener. It handles all events from Forum object. * * @see 
  8.  * ForumEvent * @author laurence.geng 
  9.  */  
  10. public interface ForumListener extends DomainObejctListener {  
  11.     /** 
  12.      * * Handle the event that a forum requests to get its threads. * * @param 
  13.      * event the event * @param result the result 
  14.      */  
  15.     public void handleGetForumThreadEvent(GetForumThreadEvent event,ResultCollector result);  
  16. }  

然后 是这个接口一个实现类,在oobbs中,做为forum的repository的实现类:ForumHibernateRepository,自然成为实现这一接口的最佳选择:

view plaincopy to clipboardprint?
  1. /** 
  2.  * * The Forum's repository with hibernate implementation, besides, it's a forum 
  3.  * listener which handle * all events come from forum object. 
  4.  */  
  5. public class ForumHibernateRepository extends AbstractHibernateRepository<Forum, Long> implements ForumRepository {  
  6.     /* 
  7.      * (non-Javadoc) 
  8.      *  
  9.      * @see 
  10.      * oobbs.domainmodel.forum.ForumListener#handleGetForumThreadEvent(oobbs 
  11.      * .domainmodel.forum.GetForumThreadEvent, 
  12.      * oobbs.domainmodel.ResultCollector) 
  13.      */  
  14.     @Overridepublic  
  15.     void handleGetForumThreadEvent(final GetForumThreadEvent event, ResultCollector result) {  
  16.         List<Thread> threads = (List<Thread>) getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {  
  17.                     @SuppressWarnings("unchecked")  
  18.                     public Object doInHibernate(Session session) throws HibernateException, SQLException {  
  19.                         logger.info("Start to load threads of forum.");  
  20.                         // Get forum.   
  21.                         String getForuumThreadHql = "from Thread as thread where thread.forum=:forum";  
  22.                         List<Thread> threads = (List<Thread>) session  
  23.                                 .createQuery(getForuumThreadHql)  
  24.                                 .setCacheable(true)  
  25.                                 .setParameter("forum", event.getSource())  
  26.                                 .setFirstResult(event.getStartIndex())  
  27.                                 .setMaxResults(event.getCount()).list();  
  28.                         return threads;  
  29.                     }  
  30.                 });  
  31.         result.add(threads);  
  32.     }  
  33. }  

最后我们看一看这一切是如被触发的。我们来看forum的这个方法:oobbs.domainmodel.forum.Forum.getThreads(int, int):

view plaincopy to clipboardprint?
  1. public List<Thread> getThreads(int startIndex, int count) {  
  2.     GetForumThreadEvent event = new GetForumThreadEvent(this, startIndex, count);  
  3.     ResultCollector result = new ResultCollector();  
  4.     forumEventDispatcher.dispatch(event, result);  
  5.     return (List<Thread>) result.getUniqueResult();  
  6. }  

  很简洁的四行代码:分别new一个event和result collector,然后用ForumEventDispatcher来dispatch这个事件,然后收集返回的处理结果。上述所有组件都是围绕这里而设计的,我们希望在领域对象的业务方法里不会出现任何repository或service,DomainEvent模式很好的满足了我们的需求,并且是以一种非常优雅而简洁的方式。

       当然,在上面讲述的整个机制中,我们漏掉了一环没有讲,那就是dispatcher是如何被实例化并完成注册listener工作的。由于oobbs使用了spring的IOC管理对象, dispatcher是由IOC创建并完成注册listener等初始化工作的。下面的类完成了这一系列工作:

view plaincopy to clipboardprint?
  1. package oobbs.infrastructure.appcontext;  
  2.   
  3. import oobbs.domainmodel.DomainObejctListener;  
  4. import oobbs.domainmodel.forum.ForumEventDispatcher;  
  5. import oobbs.domainmodel.forum.ThreadEventDispatcher;  
  6. import org.apache.log4j.Logger;  
  7. import org.springframework.beans.BeansException;  
  8. import org.springframework.beans.factory.config.BeanPostProcessor;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.ApplicationContextAware;  
  11.   
  12. /** 
  13.  * * The ApplicationBeanPostProcessor will do some initialization work when bean 
  14.  * is created by spring ioc container, * such as: Adding listeners for domain 
  15.  * event dispatchers and so on. * @author laurence.geng 
  16.  */  
  17. public class ApplicationBeanPostProcessor implements BeanPostProcessor,  
  18.         ApplicationContextAware {  
  19.     /** The Constant logger. */  
  20.     private static final Logger logger = Logger  
  21.             .getLogger(ApplicationBeanPostProcessor.class);  
  22.     /** The application context. */  
  23.     private ApplicationContext applicationContext;  
  24.   
  25.     /* 
  26.      * (non-Javadoc) * @see org.springframework .beans.factory 
  27.      * .config.BeanPostProcessor #postProcessBeforeInitialization 
  28.      * (java.lang.Object, java.lang.String) 
  29.      */  
  30.   
  31.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  32.         return bean; // we could potentially return any object reference here...  
  33.     }  
  34.   
  35.     /* 
  36.      * (non-Javadoc) * @see 
  37.      * org.springframework.beans.factory.config.BeanPostProcessor 
  38.      * #postProcessAfterInitialization(java.lang.Object, java.lang.String) 
  39.      */  
  40.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {  
  41.         logger.debug("Bean '" + beanName + "' created : " + bean.toString());  
  42.         // Adding listeners for domain event dispatchers.  
  43.         if ("forumEventDispatcher".equals(beanName)) {  
  44.             ForumEventDispatcher forumEventDispatcher = (ForumEventDispatcher) bean;  
  45.             forumEventDispatcher.addListener((DomainObejctListener) applicationContext.getBean("forumRepository"));  
  46.         }  
  47.         if ("threadEventDispatcher".equals(beanName)) {  
  48.             ThreadEventDispatcher threadEventDispatcher = (ThreadEventDispatcher) bean;  
  49.             threadEventDispatcher.addListener((DomainObejctListener) applicationContext.getBean("threadRepository"));  
  50.         }  
  51.         return bean;  
  52.     }  
  53.   
  54.     /* 
  55.      * (non-Javadoc) * @see 
  56.      * org.springframework.context.ApplicationContextAware#setApplicationContext 
  57.      * (org.springframework.context.ApplicationContext) 
  58.      */  
  59.     @Override  
  60.     public void setApplicationContext(ApplicationContext arg0) throws BeansException {  
  61.         this.applicationContext = arg0;  
  62.     }  
  63. }  


小结

  最后总结一下:其实基于数据访问的集合类(Data Access Based Collection)和领域事件(Domain Event)两者各有优劣。在实际中可以结合使用。如果只使用数据访问的集合类,则很难支持二、三级关联,而一味地使用领域事件则有会导致引入过多的事件类,引起类型爆炸。
原创粉丝点击