The Composite

Intent: We want to handle items that are hierarchically related (either through classification or like a bill of materials) as objects.

Example: The most common example of a composite is a hierarchical file system. Files are placed into folders, but folders can also contain other folders to any desired depth. The purpose of such a composite is organizing (collecting files and folders that belong together), finding (the structure can be navigated in a search), and eliminating name collision (many folders in a file system can contain a file named README.TXT, for example, with no naming collision).

images

Figure 6: Composite example diagram.

Qualities and Principles: Simple and complex structures can be modeled with no change to design. Clients couple to the interface but implementation can be hidden from them. The responsibilities of leaf (file) and node (folder) are singular and separate. Leaf and node objects can be stored and retrieved interchangeably in many cases.

Testing: Leaf objects can be tested individually. Node objects can be tested using mock leaf objects (see p. 38).

Questions and Concerns: Composites come in two general forms: classification (as in the example) and bill of materials. The latter is used to model complex entities (e.g., a budget contains categories, the categories contain line items, the line items contain details). Summing the categories might be the desired behavior.

One decision that must be addressed is whether—and to what degree—to expose the difference between leaf objects and node objects to clients. Leaf objects do not contain other elements, whereas node objects do. If this difference is exposed to clients (a node would have methods like getChild(n)in the example, where a leaf would not), then this allows clients to traverse the structure but breaks the encapsulation of type. The correct balance of these factors is determined based on the purpose of the composite in a given problem domain.

Varying node/leaf behavior can be accomplished with the visitor (see p. 56) without breaking type encapsulation.

For more information: https://tinyurl.com/y3unzs7o

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset