本文通过对老王、小王对书房、书架及各类图书的管理进行探讨,引出结构设计纹样家族中的一个重要成员--组合纹样。本文将给出这两种组合模式的典型代码实现。为了加深理解,我们将在第三部分介绍组合模式在源代码中的实际应用,并在最后总结对设计模式的研究后的一些思考。
[En]
This paper discusses the management of study, bookshelf and all kinds of books by Lao Wang and Xiao Wang, and leads to the combination pattern, which is an important member of the structural design pattern family. This paper will give the typical code implementation of the two combination patterns. In order to deepen the understanding, we will introduce the practical application of the combination pattern in the source code in the third part, and finally summarize some thoughts after the study of the design pattern.
读者可以拉取完整代码到本地进行学习,实现代码均测试通过后上传到码云。
一、引出问题
上篇文章中老王给小王买车以后,小王对老王感激涕零,看着老王凌乱的书房,小王提出要帮助老王整理整理他的书架。
小王开始了他的分析。老王平时博览群书,中文、英文、梵文...每个语种占满了书架,而每个语种中又分经济学、计算机学、社会学等等类目。这是典型的分层次结构,将语种比作是图书的子类,类目是语种的子类结构划分。
图书、语种、品类作为组织结构,它们之间没有继承关系,而是一种树形结构,可以更好地实现管理操作。
[En]
Books, languages, categories are regarded as organizational structure, there is no inheritance relationship between them, but a tree structure, which can better achieve management operations.
二、概念与使用
实际上,小王提出来的设计思路正是结构型设计模式中的组合模式,我们首先看一下组合模式的相关概念, 组合模式(Composite Pattern),又叫部分整体模式,它创建了对象组的树形结构,将对象组合成树状结构以表示" 整体-部分"的层次关系。组合模式依据 树形结构来组合对象,用来表示部分以及整体层次。
组合模式使用户能够一致地访问单个对象和组合对象,即组合允许客户以一致的方式处理单个对象和组合对象。
[En]
The composition pattern enables users to have consistent access to individual objects and combined objects, that is, the combination allows customers to deal with individual objects and combined objects in a consistent manner.
用白话解释,即在实际应用中,所有的书都是按照树的模式组合的。老王在找书的时候,无论是看某种类型的书,还是看某种语种的书,都可以用同样的姿势来保证参观的一致性。
[En]
Explained in vernacular, that is, in practical application, all books are combined according to the tree pattern. When Lao Wang is looking for books, whether he visits a certain type of book or a certain language book, he can use the same posture to ensure the consistency of the visit.