Design Mode-Combination Mode
Compose objects into tree structures to represent part-whole hiearachies. composite lets clients treat individual objects and compositions of objects uniformly. this means that the object is combined into a tree structure to represent the "part-whole" hierarchy, so that the use of a single object and a combination object is consistent.
The combination mode has three roles:
Abstract component role: defines the common methods and attributes of the composite objects.
Leaf component (Leaf) Role: this role is a Leaf object with no branches or subnodes under it.
Composite role: this role represents the branches under the composite. It combines the branches and leaves into a tree structure, and define a method to manage sub-objects.
Combined Mode class diagram:
Implementation code for each class:
Code of the abstract component:
Package com. zz. composite;/*** abstract Component interface * Copyright April 25, 2015 * created by txxs * all right reserved */public interface Component {public void operation ();}
Tree Branches Structure Code:
Package com. zz. composite; import java. util. arrayList;/*** define the branchcomponent * Copyright April 25, 2015 * created by txxs * all right reserved */public class Composite implements Component {// Component container private ArrayList
ComponentList = new ArrayList
(); // Add the public void add (Component component) {this. componentList. add (component);} // Delete the public void remove (Component component) {this. componentList. remove (component);} // obtain the sub-component public ArrayList
GetChild () {return this. getChild () ;}@ Overridepublic void operation () {// business logic code }}
Leaf Structure Code:
Package com. zz. composite;/*** define the Leaf Component * Copyright April 25, 2015 * created by txxs * all right reserved */public class Leaf implements Component {@ Overridepublic void operation () {// sales logic code }}
Advantages of the combination mode:
1. Simple calls. users do not have to worry about whether they are processing a single object or a combination object.
2. Flexible addition of nodes. To add branches or leaf nodes, you only need to find the parent node. You do not have to modify the code to add object components.
Applicable scenarios of the combination mode:
1. Describe the part and overall level structure of the object.
2. When you need to ignore the differences between individual components and composite components