Combination mode
Combined mode, which combines objects into a tree structure to represent a "partial-whole" hierarchy, combining patterns makes the user consistent with the use of individual objects and composite objects. The key to mastering the combination pattern is to understand the meaning of "part/whole" as well as "single object" and "combined object". The combination mode allows the client to complete functions that would otherwise require a Process Control statement as simple as modifying the configuration file. Classic Case: System directory structure, site navigation structure and so on. (Baidu Encyclopedia)
Combined Mode UML diagram
Combined Mode code
PackageCom.roc.composite;/*** Public Object Declaration *@authorLIAOWP **/ Public Abstract classComponent {protectedString name; PublicComponent (String name) { This. name=name; } PublicComponent () {} Public Abstract voidAdd (Component Component); Public Abstract voidRemove (Component Component); Public Abstract voidDisplayintdepth); PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } }
PackageCom.roc.composite;Importjava.util.ArrayList;Importjava.util.List;/*** Minor Point class *@authorLIAOWP **/ Public classConcretecompanyextendscomponent{PrivateList<component>list; PublicConcretecompany (String name) {Super(name); List=NewArraylist<component>(); } PublicConcretecompany () {list=NewArraylist<component>(); } @Override Public voidAdd (Component Component) {list.add (Component); } @Override Public voidRemove (Component Component) {list.remove (Component); } @Override Public voidDisplayintdepth) {StringBuilder SB=NewStringBuilder (""); for(inti = 0; I < depth; i++) {sb.append ("-"); } System.out.println (NewString (SB) + This. GetName ()); for(Component c:list) {c.display (depth+ 2); } }}
PackageCom.roc.composite;/*** Leaf node *@authorLIAOWP **/ Public classLeafextendscomponent{ PublicLeaf (String name) {Super(name); } @Override Public voidAdd (Component Component) {//TODO auto-generated Method Stub} @Override Public voidRemove (Component Component) {//TODO auto-generated Method Stub} @Override Public voidDisplayintdepth) {StringBuilder SB=NewStringBuilder (""); for(inti = 0; I < depth; i++) {sb.append ("-"); } System.out.println (NewString (SB) + This. GetName ()); }}
PackageCom.roc.composite;/*** Combined mode *@authorLIAOWP **/ Public classClient { Public Static voidMain (string[] args) {Component root=NewConcretecompany ("root"); Root.add (NewLeaf ("File A")); Root.add (NewLeaf ("File B")); Component file=NewConcretecompany ("File1"); File.add (NewLeaf ("File C")); File.add (NewLeaf ("File D")); Root.add (file); Root.display (1); }}Combination mode for Scenario 1. You want to represent the part of the object-the overall hierarchy 2. You want users to ignore the difference between a combined object and a single object, and the user will use all the objects in the composite structure uniformly.
A combined pattern of Java design patterns