23 design patterns (10) Java combination pattern

23 design patterns Part 4: Java composite pattern

introduce

The combination mode is also called part whole mode, which blurs the concepts of simple elements and complex elements in the problem of tree structure. The client program can deal with complex elements like dealing with simple elements, so as to decouple the client program from the internal structure of complex elements

Composite patterns can optimize the processing of recursive or hierarchical data structures There are many examples of hierarchical data structures that make composite patterns very useful

Class diagram

component:

Component: declare a public interface for objects participating in composition, whether composition or leaf node Leaf: represents the leaf node object in the combination, and the leaf node has no child nodes Composite: represents the object with sub objects participating in the composition, and gives the behavior of branch purchase

example

FolderComponent

FileLeaf

FolderComposite

Client

Output results:

FileLeaf:runnable file FolderComposite---name:new folder FolderComposite---component-name:content1 in new folder FolderComposite---component-name:content2 in new folder

Usage scenario

Composite mode is applicable in the following cases:

1. You want to represent the part of the object - the overall hierarchy. 2. You want users to ignore the difference between composite objects and single objects. Users will use all objects in the composite structure uniformly.

summary

The composite pattern decouples the internal structure of the client program and complex elements, so that the client program can deal with complex elements as simple elements. If you want to create a hierarchy in which all elements can be treated in the same way, the combination mode is the ideal choice. This chapter uses a file system example to illustrate the use of composite patterns. In this example, both files and directories implement the same interface, which is the key to the composite pattern. By implementing the same interface, you can treat files and directories in the same way, so as to store files or directories as child elements of directories.

Transferred from: Java confidant

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>