定义
将对象组合成树形结构以表示“部分-整体”的层次结构。
组合模式的分类:
- 透明组合模式: 透明组合模式中,抽象构件角色中声明了所有对于管理成员对象的方法,透明组合模式是组合模式的标准形式。
- 安全组合模式: 安全组合模式中,在抽象构件角色中没有声明任何用于管理成员对象的方法,而是在容器构件类中声明并实现这些方法。
组合模式的结构:
1、Component(抽象构件)
它可以是接口或抽象类,以叶子构件和容器构件对象声明接口,在该角色中可以包含所有子类共有行为的声明和实现。在抽象构件中定义了访问及管理它的子构件的方法,如增加子构件、删除子构件、获取子构件等。
2、Composite(容器构件)
它在组合结构中表示容器节点对象,容器节点包含子节点,其子节点可以是叶子节点,也可以是容器节点,它提供一个集合用于存储子节点,实现了抽象构件中定义的行为,包括哪些访问及管理子构件的方法,在其业务方法中可以递归调用其子节点的业务方法。
3、Leaf(叶子构件)
它在组合结构中表示叶子节点对象,叶子节点没有子节点,它实现了在抽象构件中定义的行为。对于那些访问及管理子构件的方法,可以通过异常等方式进行处理。
优缺点
优点:
- 组合模式可以清晰的定义分层次的复杂对象,表示对象的全部或部分层次,方便对整个层次结构进行控制
- 客户端可以一致地使用一个组合结构或其中单个对象,不必关心处理的是单个对象还是整个组合结构,简化了客户端代码
- 增加新的容器构件和叶子构件都很方便,无须对现有类库进行任何修改,符合“开闭原则”
组合模式为树形结构的面向对象实现提供了一种灵活的解决方案,通过叶子对象和容器对象的递归组合,可以形成复杂的树形结构,但对树形结构的控制却非常简单
缺点:
使得设计更加复杂,客户端需要花更多时间理清类之间的层次关系。
-
适用场景
在软件开发中存在大量的树形结构,因此组合模式是一种使用频率较高的结构型设计模式,Java SE中的AWT和Swing包的设计就基于组合模式。除此以外,在XML解析、组织结构树处理、文件系统设计等领域,组合模式都得到了广泛应用。
在具有整体和部分的层次结构中,希望通过一种方式忽略整体与部分的差异,客户端可以一致地对待它们。
- 在一个使用面向对象语言开发的系统中需要处理一个树形结构。
在一个系统中能够分离出叶子对象和容器对象,而且它们的类型不固定,需要增加一些新的类型。
组合模式实现
抽象构件
public abstract class OrganizationComponent {private String name; // 名字private String des; // 说明protected void add(OrganizationComponent organizationComponent) {//默认实现throw new UnsupportedOperationException();}protected void remove(OrganizationComponent organizationComponent) {//默认实现throw new UnsupportedOperationException();}//构造器public OrganizationComponent(String name, String des) {super();this.name = name;this.des = des;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDes() {return des;}public void setDes(String des) {this.des = des;}//方法print, 做成抽象的, 子类都需要实现protected abstract void print();}
容器构件 —> 学校类
public class University extends OrganizationComponent {List<OrganizationComponent> organizationComponents = new ArrayList<OrganizationComponent>();// 构造器public University(String name, String des) {super(name, des);}// 重写add@Overrideprotected void add(OrganizationComponent organizationComponent) {organizationComponents.add(organizationComponent);}// 重写remove@Overrideprotected void remove(OrganizationComponent organizationComponent) {organizationComponents.remove(organizationComponent);}@Overridepublic String getName() {return super.getName();}@Overridepublic String getDes() {return super.getDes();}// print方法,就是输出University 包含的学院@Overrideprotected void print() {System.out.println("--------------" + getName() + "--------------");//遍历 organizationComponentsfor (OrganizationComponent organizationComponent : organizationComponents) {organizationComponent.print();}}}
容器构件 —> 学院类
public class College extends OrganizationComponent {//List 中 存放的DepartmentList<OrganizationComponent> organizationComponents = new ArrayList<OrganizationComponent>();// 构造器public College(String name, String des) {super(name, des);}// 重写add@Overrideprotected void add(OrganizationComponent organizationComponent) {// 将来实际业务中,Colleage 的 add 和 University add 不一定完全一样organizationComponents.add(organizationComponent);}// 重写remove@Overrideprotected void remove(OrganizationComponent organizationComponent) {organizationComponents.remove(organizationComponent);}@Overridepublic String getName() {return super.getName();}@Overridepublic String getDes() {return super.getDes();}// print方法,就是输出University 包含的学院@Overrideprotected void print() {System.out.println("--------------" + getName() + "--------------");//遍历 organizationComponentsfor (OrganizationComponent organizationComponent : organizationComponents) {organizationComponent.print();}}}
叶子节点 —> 专业类
public class Department extends OrganizationComponent {//没有集合public Department(String name, String des) {super(name, des);}//add , remove 就不用写了,因为他是叶子节点@Overridepublic String getName() {return super.getName();}@Overridepublic String getDes() {return super.getDes();}@Overrideprotected void print() {System.out.println(getName());}}
测试 ```java public class Client { public static void main(String[] args) {
//从大到小创建对象 学校OrganizationComponent university = new University("清华大学", " 中国顶级大学 ");//创建 学院OrganizationComponent computerCollege = new College("计算机学院", " 计算机学院 ");OrganizationComponent infoEngineercollege = new College("信息工程学院", " 信息工程学院 ");
//创建各个学院下面的系(专业)computerCollege.add(new Department("软件工程", " 软件工程不错 "));computerCollege.add(new Department("网络工程", " 网络工程不错 "));computerCollege.add(new Department("计算机科学与技术", " 计算机科学与技术是老牌的专业 "));//infoEngineercollege.add(new Department("通信工程", " 通信工程不好学 "));infoEngineercollege.add(new Department("信息工程", " 信息工程好学 "));//将学院加入到 学校university.add(computerCollege);university.add(infoEngineercollege);university.print();//infoEngineercollege.print();}
}
<a name="lSgnx"></a># 拓展<a name="11hH7"></a>## Java集合类HashMap 源码分析HashMap 提供了putAll方法,可以将另一个Map对象放入自己的存储空间中,如有相同的key则会覆盖之前的key值所对应的value值。<br /><br />putAll接收的参数为父类Map类型,所以hashmap是一个容器类,map的子类为叶子类,当然如果map的其它子类也实现了putAll方法,那么他们既是容器类,又都是叶子类;<br />同理,ArrayList 中的 addAll(Collection<? extends E> c) 方法也是一个组合模式的应用。<a name="c7f6582c"></a>## Mybatis SqlNode中的组合模式MyBatis 的强大特性之一便是它的动态SQL,其通过 if, choose, when, otherwise, trim, where, set, foreach 标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。<br />Mybatis在处理动态SQL节点时,应用到了组合设计模式,MyBatis会将映射文件中定义的静态SQL节点、文本节点等解析成对应的SqlNode实现,形成树形结构。<a name="NA7aG"></a>### 动态SQL – IF```java<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG WHERE state = ‘ACTIVE’<if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></select>
动态SQL – choose, when, otherwise
<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG WHERE state = ‘ACTIVE’<choose><when test="title != null">AND title like #{title}</when><when test="author != null and author.name != null">AND author_name like #{author.name}</when><otherwise>AND featured = 1</otherwise></choose></select>
动态SQL – where
<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG<where><if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></where></select>
动态SQL – foreach
<select id="selectPostIn" resultType="domain.blog.Post">SELECT * FROM POST P WHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach></select>
