本文是基于上一篇‘业务建模战术’的实践,主要讲解‘发表帖子’场景的业务建模,包括:业务建模、业务模型、示例代码;示例代码会使用java编写,文末附有github地址。相比于《领域驱动设计》原书中的航运系统例子,社交服务系统的业务场景对于大家更加熟悉,相信更好理解。本文是【DDD】系列文章的其中一篇,其他可参考:使用领域驱动设计思想实现业务系统
业务建模
在大家的常识中,每个人都有自己的观点,并可以发表自己的观点,在社区中便表现为:发布帖子。那么谁发布帖子呢? 很明显是帖子作者,于是我们便可以得到如下描述:帖子作者发布帖子。从上述描述中,我们很容易得到如下几个实体及其行为:帖子作者(PostAuthor)、帖子(Post),而PostAuthor拥有‘发布帖子’的业务行为,我们记着:posting()。
我们再细化现有的模型中的实体。作为实体,必须有一个唯一业务标识,我们为PostAuthor添加一个'作者编号'(authorId),为Post添加一个‘帖子编号’(postId);PostAuthor可能还存在其他一些属性,我们暂且不管,因为对于我们现在的业务场景无关紧要;再看Post实体,很明显帖子有‘帖子标题’(postTitle)、‘帖子正文’(postContent)、‘帖子发布时间’(postingTime)等等。同时,从业务上要求:帖子发帖时间即为帖子发布动作发生的时间点,帖子的作者是不能为空的,帖子的内容不能为空,帖子的标题可以为空。
此外,为了减少垃圾帖对社区的负面影响,对于‘帖子内容'强制要求帖子内容长度必须不少于16个汉字,字母和数字等同于汉字处理。
总结可以得到‘发布帖子’场景的业务模型描述:
- 帖子作者发布帖子,帖子标题可以为空,帖子内容不能为空,且不少于16个汉字。
鉴于PostAuthor和Post关系紧密,我们姑且将其和Post放到同一个模块,但是Post看上去并不是PostAuthor的根实体,有点怪怪的感觉,暂且不追究。
业务模型
综上,于是我们得到如下的业务模型:
代码示例
据此写出简单的示例代码:
1 /** 2 * 帖子实体 3 * @author DAOQIDELV 4 * @CreateDate 2017年9月16日 5 * 6 */ 7 public class Post { 8 9 /** 10 * 帖子id 11 */ 12 private long id; 13 /** 14 *帖子作者 15 */ 16 private long authorId; 17 /** 18 * 帖子标题 19 */ 20 private String title; 21 /** 22 * 帖子源内容 23 */ 24 private String sourceContent; 25 /** 26 * 发帖时间 27 */ 28 private Timestamp postingTime; 29 30 public Post(long authorId, String title, String sourceContent) { 31 this.setAuthorId(authorId); 32 this.setTitle(title); 33 this.setSourceContent(sourceContent); 34 this.postingTime = new Timestamp(System.currentTimeMillis()); 35 } 36 37 /** 38 * @param authorId the authorId to set 39 */ 40 public void setAuthorId(long authorId) { 41 Assert.isTrue(authorId > 0, "Post's authorId must greater than ZERO."); 42 this.authorId = authorId; 43 } 44 45 /** 46 * @param sourceContent the sourceContent to set 47 */ 48 public void setSourceContent(String sourceContent) { 49 Assert.isTrue(!StringUtils.isEmpty(sourceContent), "Post's sourceContent must NOT be empty."); 50 this.sourceContent = sourceContent; 51 } 52 53 //ignore some setter/getter 54 55 }