“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Portfolio model

Composite Pattern, also called partial whole Pattern, is used to treat a group of similar objects as a single object. The composite pattern combines objects based on a tree structure, which is used to represent both part and whole hierarchies. You can create a new object by combining one or more simple objects. The original objects are the elements of the object. This type of design pattern is a structural pattern that creates a tree structure of groups of objects.

The composite pattern can also be thought of as a way of iteratively calling some objects.

Advantages of combination mode:

  • 1. High-level modules are easy to call.
  • 2. Nodes are added freely.

Case analysis

Let’s take a look at the composite pattern with a familiar example. This example comes from the soft exam afternoon questions in previous years.

The following figure preconstructs a file directory tree, which is similar to the relationship between folders and files we commonly use. A folder can contain files and folders, and a Layer 2 folder can contain files and folders. One layer of folders is the parent of layer 2 folders and files. Layer 3 folders or files are subclasses of Layer 2 folders. Similar to this tree structure, the combination of design pattern to design.

Analysis of the

All files and folders have names, sizes, and formats. You can modify, delete, and move files and folders. These common operations and attribute values can then be extracted into an abstract class. It then replaces the underlying data information with a subattribute.

The development of

As you can see from the figure, an AbstractFile abstract class can be created after extracting the public properties and methods. Including: folder, file name; Methods for adding files or folders; Method of deleting files or folders; A method for moving files or folders; Method to get a list of file subfiles. AbstractFile abstract classes are as follows:

/** * @ClassName AbstractFile * @Description: Public abstract class AbstractFile {protected String fileName; /** * Public void printFileName(){system.out.println (fileName); /** public void printFileName(){system.out.println (fileName); Public abstract Boolean addChild(AbstractFile AbstractFile); Public abstract Boolean delChild(AbstractFile AbstractFile); Public abstract Boolean removeChild(AbstractFile AbstractFile); Public abstractList <AbstractFile> getChildfilelist (); }Copy the code

Now write the concrete implementation class of the file, because the file has no child files or folders, so when we get the list of file child files, we return null by default. It is important to note that, as in our business, the basic processes and attributes of the business need to be understood when coding implementations. The actual business logic can be added before the method returns a value, returning true on success; If processing fails, return false. The system returns false by default;

The File File has the following class:

/** * @ClassName File * @Description: * @author Public Id: * @version V1.0 **/ public class File extends AbstractFile {public File(String name){this.filename = name; } @Override public boolean addChild(AbstractFile abstractFile) { return false; } @Override public boolean delChild(AbstractFile abstractFile) { return false; } @Override public boolean removeChild(AbstractFile abstractFile) { return false; } @Override public List<AbstractFile> getChildAbstractFileList() { return null; }}Copy the code

When creating sub-files or collections of files under folders, it is necessary to pay attention to obtaining sub-files under folders and files and folders under sub-folders, which need to be iterated layer by layer. In this paper, as an example, we directly use new to create them. That’s something to be aware of.

Folder The Folder classes are as follows:

/** * @ClassName Folder * @Description: Public Class Folder extends AbstractFile {private List<AbstractFile> List; public Folder(String name) { this.fileName = name; this.list = new ArrayList<AbstractFile>(); } @Override public boolean addChild(AbstractFile abstractFile) { this.list.add(abstractFile); return false; } @Override public boolean delChild(AbstractFile abstractFile) { return false; } @Override public boolean removeChild(AbstractFile abstractFile) { return false; } @Override public List<AbstractFile> getChildAbstractFileList() { return list; }}Copy the code

run

The above basic modules have been built, including Folder and File. They all have a common approach. Now change the method of traversing the file and folder names in the directory, printing the file name and folder name.

First, initialize the directory format of a folder and file: the root directory is: D:\, there are several folders respectively: “Linux” and “Win” two folders, and there are lower subset files and folders under these two folders. Write a method printFileTree to output File and Folder name. Since the entire directory tree is built based on Folder and File, printFileTree needs to be used iteratively in the output process. The specific method is as follows:

/** * @ClassName Folder * @Description: * @author Public Id: Java full stack architect * @version V1.0 **/ public class MainApp {public static void main(String[] args) {AbstractFile rootFolder =new Folder("D:\\"); AbstractFile linuxFolder =new Folder("Linux"); AbstractFile winFolder =new Folder("Win"); AbstractFile jdkFolder =new Folder("jdk"); AbstractFile testFile =new File("test.java"); AbstractFile linuxTestFile =new File("Linux_test.java"); rootFolder.addChild(linuxFolder); rootFolder.addChild(winFolder); winFolder.addChild(jdkFolder); jdkFolder.addChild(testFile); linuxFolder.addChild(linuxTestFile); printFileTree(rootFolder); } public static void printFileTree(AbstractFile abstractFile) { abstractFile.printFileName(); List<AbstractFile> abstractFileList = abstractFile.getChildAbstractFileList(); if (abstractFileList == null) { return; } else { for (AbstractFile abstractFiles : abstractFileList) { printFileTree(abstractFiles); }}}}Copy the code

The output is as follows, showing the hierarchy of files and directories.

D:\ Linux Linux_ nuggets Java Win JDK test_ nuggets JavaCopy the code

conclusion

Ok, a simple combination mode is introduced to complete, learning design mode, as far as possible combined with the familiar case analysis, so that there will be twice the result with half the effort, but also easier to understand. Try using design patterns in your projects.

Thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.