One , Basic introduction

Combination mode , Combine objects into a tree structure to represent objects “ whole - part ” The hierarchy of , An object structure pattern .

Because there are a lot of tree structures in software development , Therefore, combination mode is a kind of structural design mode with high frequency of use ,Java
SE In AWT and Swing Package design is based on the combination pattern . in addition to , stay XML analysis , Organization structure tree processing , File system design and other fields , Combination pattern has been widely used .

Classification of combinatorial patterns :

1, Transparent combination mode

In transparent combination mode , All the methods for managing member objects are declared in the abstract component role , Transparent composition pattern is the standard form of composition pattern .

2, Security combination mode

In security combination mode , No method for managing member objects is declared in the abstract component role , Instead, these methods are declared and implemented in the container component class .

Two , The structure of combination mode

1,Component( Abstract component )

It can be an interface or an abstract class , Declare interfaces with leaf component and container component objects , In this role, you can include declarations and implementations of behaviors common to all subclasses . The methods of accessing and managing its sub components are defined in the abstract component , For example, add sub components , Delete subcomponents , Get subcomponents, etc .

2,Composite( Vessel components )

It represents a container node object in a composite structure , Container node contains child nodes , Its child nodes can be leaf nodes , It can also be a container node , It provides a collection for storing child nodes , The behavior defined in the abstract component is implemented , What are the methods to access and manage the subcomponents , In its business method, the business method of its child node can be called recursively .

3,Leaf( Leaf component )

It represents the leaf node object in the composite structure , The leaf node has no children , It implements behaviors defined in abstract components . For those methods of accessing and managing subcomponents , It can be handled by exception and so on .

The key of composition pattern is to define an abstract component class , It can represent the leaf , It can also represent the container , The client program for the abstract component class , It's not necessary to know whether it represents a leaf or a container , It can be treated uniformly . At the same time, an aggregation relation is established between the container object and the abstract component class , You can include leaves in a container object , You can also include containers , To achieve recursive combination , Form a tree structure .

Three , Advantages and disadvantages of combination mode

 

1, advantage

(1) Composite pattern can clearly define hierarchical complex objects , Represents all or part of the hierarchy of an object , It allows clients to ignore the differences in hierarchy , It is convenient to control the whole hierarchy .

(2) Clients can consistently use a composite structure or a single object within it , You don't have to care whether you're dealing with a single object or an entire composite structure , Simplified client code .

(3) It is convenient to add new container component and leaf component in combination mode , There is no need to make any changes to the existing class library , accord with “ Open close principle ”.

(4) The combination pattern provides a flexible solution for the object-oriented implementation of tree structure , Through the recursive combination of leaf object and container object , It can form complex tree structure , But the control of tree structure is very simple .

2, shortcoming

(1) Make the design more complicated , The client needs to spend more time clarifying the hierarchical relationship between classes .

(2) When adding new components, it is difficult to limit the component types in the container .

Four , Usage scenarios of combination mode

1, In a hierarchy of whole and part , Hope to ignore the difference between the whole and the part in a way , Clients can treat them consistently .

2, In a system developed with object-oriented language, we need to deal with a tree structure .

3, In a system, the leaf object and container object can be separated , And their types are not fixed , Some new types need to be added .

Five , Combination mode to realize the display of school departments

1, Abstract component
package designMode.advance.composite; public abstract class
OrganizationComponent { private String name; // name private String des; // explain
protected void add(OrganizationComponent organizationComponent) { // Default implementation throw
new UnsupportedOperationException(); } protected void
remove(OrganizationComponent organizationComponent) { // Default implementation throw new
UnsupportedOperationException(); } // constructor 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; } // method print, Make it abstract , Subclasses need to be implemented protected abstract void print(); }
2, Vessel components --> School
package designMode.advance.composite; import java.util.ArrayList; import
java.util.List; public class University extends OrganizationComponent {
List<OrganizationComponent> organizationComponents = new
ArrayList<OrganizationComponent>(); // constructor public University(String name,
String des) { super(name, des); } // rewrite add @Override protected void
add(OrganizationComponent organizationComponent) {
organizationComponents.add(organizationComponent); } // rewrite remove @Override
protected void remove(OrganizationComponent organizationComponent) {
organizationComponents.remove(organizationComponent); } @Override public String
getName() { return super.getName(); } @Override public String getDes() { return
super.getDes(); } // print method , It's output University Colleges included @Override protected void
print() { System.out.println("--------------" + getName() + "--------------");
// ergodic organizationComponents for (OrganizationComponent organizationComponent :
organizationComponents) { organizationComponent.print(); } } }
 3, Vessel components --> College
package designMode.advance.composite; import java.util.ArrayList; import
java.util.List; public class College extends OrganizationComponent { //List in
Stored Department List<OrganizationComponent> organizationComponents = new
ArrayList<OrganizationComponent>(); // constructor public College(String name, String
des) { super(name, des); } // rewrite add @Override protected void
add(OrganizationComponent organizationComponent) { // In the actual business in the future ,Colleage Of add and
University add It doesn't have to be exactly the same organizationComponents.add(organizationComponent); } //
rewrite remove @Override protected void remove(OrganizationComponent
organizationComponent) { organizationComponents.remove(organizationComponent);
} @Override public String getName() { return super.getName(); } @Override
public String getDes() { return super.getDes(); } // print method , It's output University
Colleges included @Override protected void print() { System.out.println("--------------" +
getName() + "--------------"); // ergodic organizationComponents for
(OrganizationComponent organizationComponent : organizationComponents) {
organizationComponent.print(); } } }
4, Leaf node --> Professional
package designMode.advance.composite; public class Department extends
OrganizationComponent { // There is no set public Department(String name, String des) {
super(name, des); } //add , remove You don't have to write , Because he's a leaf node @Override public String
getName() { return super.getName(); } @Override public String getDes() { return
super.getDes(); } @Override protected void print() {
System.out.println(getName()); } }
5, Test class
package designMode.advance.composite; public class Client { public static void
main(String[] args) { // Creating objects from large to small school OrganizationComponent university = new
University(" Tsinghua University ", " Top universities in China "); // establish college OrganizationComponent computerCollege =
new College(" school of computing ", " school of computing "); OrganizationComponent infoEngineercollege =
new College(" College of Information Engineering ", " College of Information Engineering "); // Create departments under each college ( major ) computerCollege.add(new
Department(" software engineering ", " Software engineering is good ")); computerCollege.add(new Department(" Network engineering ", "
Good network engineering ")); computerCollege.add(new Department(" Computer science and technology ", " Computer science and technology is an old specialty
")); // infoEngineercollege.add(new Department(" communication engineering ", " Communication engineering is hard to learn "));
infoEngineercollege.add(new Department(" Information Engineering ", " Information engineering is studious ")); // Add the college to school
university.add(computerCollege); university.add(infoEngineercollege);
university.print(); //infoEngineercollege.print(); } }

Six ,Java Collection class HashMap  Source code analysis

HashMap Provided putAll method , You can take another one Map Object into its own storage space , If the same key The previous key Value value value .

1, Code instance
package designMode.advance.composite; import java.util.HashMap; import
java.util.Map; public class HashMapComposite { public static void main(String[]
args) { Map<Integer,String> universityMap = new HashMap<>();
universityMap.put(1," Tsinghua University "); universityMap.put(2," Peking University ");
universityMap.put(3," liaoning shihua university "); System.out.println("universityMap: " +
universityMap); Map<Integer,String> collegeMap = new HashMap<>();
collegeMap.put(1," school of computing "); collegeMap.put(4," College of Information Engineering ");
System.out.println("collegeMap: " + collegeMap);
universityMap.putAll(collegeMap);
System.out.println("universityMap.putAll(collegeMap),"+universityMap); } }
2, console output

3, Source code analysis

putAll The received parameter is the parent class Map type , therefore hashmap Is a container class ,map Its subclass is leaf , Of course, if map Other subclasses of are also implemented putAll method , So they are container classes , They're all leaves ;

In the same way ,ArrayList In addAll(Collection<? extends E> c) Method is also an application of combination pattern ;

Seven ,Mybatis SqlNode The combination mode in the network

MyBatis One of the most powerful features of the Internet is its dynamic SQL, It passed if, choose, when, otherwise, trim, where, set,
foreach label , Can be combined into a very flexible SQL sentence , So as to improve the efficiency of developers .

dynamic SQL – IF
<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>
dynamic 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>
dynamic 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>
dynamic 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>

Mybatis In dealing with the dynamic SQL Node time , It is applied to combination design pattern ,MyBatis The static SQL node , Text nodes are parsed into corresponding SqlNode realization , Form a tree structure .

Technology