Concise combination mode (4.3)

Source: Internet
Author: User

Concise combination mode (4.3)

There are too many things on the desktop, so people use various containers to organize things. Combine a series of basic objects (leaf objects) into one container, and the container can be further put into another container.


Composite Pattern)Components are combined to formTree Structure. In the computer field, tree structures are widely used, such as file systems, menu systems, GUI, Java (Data Structure) containers, and XML files. The main points of the combination mode are:Leaf objects and various containers can be processed in a unified manner. The concept of generic operations for encapsulating containers and leaf objects is usually referred to as components/Component.

Programmers usually like to use tree-structured words to introduce the combination mode. For example, the general substitution word of Component is Node, composite/synthesis is called intermediate Node or branch, and the basic object is called Leaf.

Container equals leaf

Assume that the Client copies/copy () File system elements. In this case, whether it is a Folder or a File, you can use the abstract type Node to encapsulate general operations on the container Folder and leaf File copy (), node is the Folder and File parent types. The container Folder needs to store and manage the nodes it saves (which can be folders or files ). In composite mode, the Client does not need to worry about whether the file system elements to be processed are leaves. "operations on composite objects are consistent with operations on a single object ".

Routine 6 2 Container package structure. composite; public interface Node {public void copy (); // define unified interface} package structure. composite; import java. util. arrayList; public class Folder implements Node {private String folderName; // used to store the Folder or file private ArrayList under this Folder
 
  
NodeList = new ArrayList <> (); public Folder (String folderName) {this. folderName = folderName;} public void add (Node node) {// add a file or folder nodeList. add (node);}/*** recursively copy yourself and all sub-elements */@ Override public void copy () {System. out. println ("Copy Folder:" + folderName); for (Node x: nodeList) {x. copy ();}}}
 
Standard combination mode structure. It has three roles: Component, such as Node, Leaf Node Leaf, and intermediate Node Composite. Generally, ArrayList is used to accommodate other components. To Manage Sub-nodes, you must add or delete them.

Let's look at another example. In the daily organizational structure, employees/Employee constitute a department and a company. Assume that you need to calculate the total salary of the company. At this time, you do not need to be in the company class equivalent to Node or department class equivalent to Folder.All elements are Employee objects.And the company's CEO and department manager's attribute ArrayList Include its subordinates/subordinates. In this structure, the Employee can have a reference pointing to the parent node for ease of operation.

Routine 6-4 container package structure. composite; import java. util. ArrayList; public class Employee {String name; int salary; ArrayList
 
  
Subordinates; boolean isLeaf; private Employee parent = null; public Employee (String name, int salary) {this (null, name, salary);} public Employee (Employee parent, String name, int salary) {this. parent = parent; this. name = name; this. salary = salary; subordinates = new ArrayList <> ();} public void setLeaf (boolean B) {isLeaf = B; // if true, do not allow children} public int getSalary () {return Salary;} public String getName () {return name ;} /*************************************** * ********/public boolean add (Employee e) {if (! IsLeaf) subordinates. add (e); return isLeaf;} public void remove (Employee e) {if (! IsLeaf) subordinates. remove (e);} // tree search public Employee getChild (String name) {Employee newEmp = null; if (this. getName (). equals (name) {return this;} for (Employee x: subordinates) {newEmp = x. getChild (name); if (newEmp! = Null) break;} return newEmp;} public int getSalaries () {int sum = salary; for (Employee x: subordinates) {sum + = x. getSalaries () ;}return sum ;}}
 

When using the combination mode, a troublesome task is to construct a tree structure of various components. As you do in GUI programming (a well-known application in a combination mode), you can write a lot of parent. add (child ). The code for building the data tree can be stored in the Customer Code, or encapsulated into a separate class such as Model. The root element of a data tree is usually stored in customer code.

Component Interface

[GoF] highlights a theoretical topic when introducing the combination mode:Degraded inheritance.

Components/Component only contain the common operations of containers/Composite and leaves-basic operations, or various operations that the container uses to manage its child elements, such as add () and getChildren ()?

If the Component only contains basic operations, the container must inherit the Component extension. When the customer declares an element as Component, the container extension method cannot be used directly. The Component must be modeled as Composite. In other words, the customer regards all component objects as leaves.

On the other hand, if the component contains the management methods required by the container, such as add (), the inheritance of the leaf object becomes the restriction Inheritance/degradation inheritance. When a customer declares an element as Component, the customer regards all the Component objects as containers. After the leaf object is replaced by the application environment, exceptions may occur. This implementation method is called in [GoF]Transparency-"You can use all components in a consistent manner". In fact, it is no essentially different from the former in terms of "Transparency,The former regards all component objects as leaves, and the latter regards all component objects as containers. The former avoids degradation inheritance and makes the entire system conform to the LSP. The latter avoids downward Styling or forced type conversion.. This method is called the Big interface combination mode.

The large interface combination mode treats all components as containers and provides more convenience in actual programming. The routines 6-4 are typical. The application scenario is that programmers have reasonable reasons to regard all components as containers and define the components as leaves. Reasonable default code for add () and getChild () to avoid degradation of inheritance.The leaf rewrite Component method, whether it is an empty implementation or throw an exception, is usually not desirable. In addition, the override method of the subclass in Java cannot throw an exception larger than the parent type. In other words, if getChild () of the parent type does not throw an exception, the code of the subclass cannot throw a check exception.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.