Composite Pattern)

Source: Internet
Author: User

Composite Pattern)
1. What is a combination mode? The combination mode provides a hierarchical structure that allows us to ignore the differences between objects and object sets. The caller does not know whether an object is an object or a group of objects, in the combination mode, the caller does not need to know these two. for example, suppose we want to describe the file system. There are files and folders in the file system, and folders and files in the folder... Yes, this is a hierarchical structure. Just like a menu, the menu contains menu items and sub-menus .. The hierarchy is also a tree structure. We can easily think of defining a Node class that contains a group of pointers to children, to construct a complete tree, our class diagram will be like this: Note: File only supports the operations listed in the class diagram, the Folder class supports the basic design of all inherited operation classes. Using this class structure, you can describe the file system. The following code is used to implement the definition of the Directory base class: package CompositePattern; import java. util. arrayList;/*** defines the Directory class * @ author ayqy */public abstract class Directory {String name; String description; ArrayList <Directory> files; /*** Add the specified file/folder to the directory * @ param dir the file/folder to be added * @ return add successful/failed */Public boolean add (Directory dir) {throw new UnsupportedOperationException (); // operation exception thrown by default}/*** Delete the specified file/folder in the directory * @ param dir file/folder to be deleted * @ return Delete successful/failed */public boolean remove (Directory dir) {throw new UnsupportedOperationException (); // operation exception thrown by default}/*** clear all files and folders in the directory * @ return clear success/failure */public boolean clear () {throw new UnsupportedOperationException (); // operation exception thrown by default} public ArrayList <Director Y> getFiles () {throw new UnsupportedOperationException (); // operation exception thrown by default}/*** print Output */public abstract void print (); public String getName () {return name;} public String getDescription () {return description;} public String toString () {return name + description;} P.S. note that the processing method (throwing an exception) specific to the Folder in the base class can also be done in a more harmonious way. Each has its own advantages and disadvantages, the reason for throwing an exception is described in the following article. Note that we define an abstract print method in the base class and want to use the print method to output the entire file tree, combination Mode The File class is package CompositePattern; /*** implementation File class * @ author ayqy */public class File extends Directory {public File (String name, String desc) {this. name = name; this. description = desc;} @ Override public void print () {System. out. print (this. toString (); // output File information} the File class is very simple, because the default implementation of operations not supported by File in the base class (throwing an exception ), so the File is quite slim. Next, the Folder class: package CompositePattern; import java. util. ArrayList;/*** implement the Folder class * @ author ayqy */public class Folder extends Directory {public Folder (String name, String desc) {this. name = name; this. description = desc; this. files = new ArrayList <Directory> () ;}@ Override public void print () {// print the Folder Information System. out. print (this. toString () + "("); // print all files and sub-files in the Directory for (Directory dir: files) {dir. print (); System. out. print (",");} // print the end mark of folder traversal. M. out. print (")") ;}@ Override public boolean add (Directory dir) {if (files. add (dir) return true; else return false;} @ Override public boolean remove (Directory dir) {if (files. remove (dir) return true; else return false;} @ Override public boolean clear () {files. clear (); return true ;}@ Override public ArrayList <Directory> getFiles () {return files ;}} the Folder class provides its own implementation for all supported operations, and made some articles in the print method, using a very simple The loop achieves print output for all the child nodes of the current node (which is easy to think? That's right, it's a Paster pattern). It seems incredible, but this is one of the benefits of using a composite pattern (providing natural soil for recursion) 3. in the results example, the classes required to describe the file system are implemented. You can test them to see the results: The test class code is as follows: package CompositePattern; /*** implement a Test class * @ author ayqy */public class Test {public static void main (String [] args) {/* construct the file tree * // * C a.txt B .txt system sys. dat windows win32 settings log.txt win32.config */Directory dir = new Folder ("C", ""); dir. add (new File ("a.txt", ""); dir. add (new File ("B .txt ","" ); Directory subDir = new Folder ("system", ""); subDir. add (new File ("sys. dat "," "); dir. add (subDir); Directory subDir2 = new Folder ("windows", ""); Directory subDir3 = new Folder ("win32 ",""); subDir3.add (new Folder ("settings", ""); subDir3.add (new File ("log.txt", ""); subDir2.add (subDir3 ); subDir2.add (new File ("win32.config", ""); dir. add (subDir2); dir. print (); // print the output file tree} run the following results: 1C(a.txt, B. Txt, system (sys. dat,), windows (win32 (settings (), log.txt,), win32.config,),), and the expected results are basically the same, but the shortcomings in the United States are: there are redundant comma delimiters. To eliminate unnecessary commas, we need to show that the loop does not output commas when taking the last line, it is easy to use an explicit iterator to output a comma for the rest of the time (isn't hasNext used to determine if it's the last one? Do not forget that ArrayList supports iterators). Let's modify the print method: public void print () {// print the Folder's own information System. out. print (this. toString () + "("); // print all files and sub-files in the Directory Iterator <Directory> iter = getFiles (). iterator (); while (iter. hasNext () {Directory dir = iter. next (); dir. print (); if (iter. hasNext () {System. out. print (",") ;}// print the end mark of folder traversal: System. out. print (")");} removes unnecessary commas (,).

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.