Let's take a look at the definition of the combinatorial pattern: " combine objects into a tree structure to represent the ' part-whole ' hierarchy." The combined mode makes the user consistent with the use of individual objects and composite objects. "
/** * Abstract Component */public interface Component {void operation ();} /** * Leaf Components */interface leaf extends component{}/** * Container Components */interface Composite extends component{}
public interface Abstractfile {void Killvirus ();} Class ImageFile implements Abstractfile{private string Name;public imagefile (string name) {super (); this.name = name;} @Overridepublic void Killvirus () {System.out.println ("image file" +name+ "for Avira");}} Class Textfile implements Abstractfile{private string Name;public textfile (string name) {super (); this.name = name;} @Overridepublic void Killvirus () {System.out.println ("text file" +name+ "for Avira");}} Class Videofile implements Abstractfile{private string Name;public videofile (string name) {super (); this.name = name;} @Overridepublic void Killvirus () {System.out.println ("video file" +name+ "for Avira");}} Class Folder implements Abstractfile{private String name;private list<abstractfile> List = new arraylist< Abstractfile> ();p ublic Folder (String name) {super (); this.name = name;} public void Add (Abstractfile file) {list.add (file);} public void Remove (Abstractfile file) {list.remove (file);} Public abstractfile getchildr (int index) {return list.get (index);} @Overridepublic VOID Killvirus () {System.out.println ("folder" +name+ "for Avira"); for (Abstractfile file:list) {File.killvirus ();}}}
Test:
public class Client {public static void Main (string[] args) {abstractfile f2,f3,f4,f5; Folder F1 = new Folder ("My Collection"), F2 = new ImageFile ("Mm.jpg"), F3 = new Textfile ("123.txt"); F1.add (F2); F1.add (F3); Folder F11 = new Folder ("My Movie"); f4 = new Videofile ("LOL"); f5 = new Videofile ("Condor mp4"); F11.add (F4); F11.add (F5); F1 . Add (F11); F1.killvirus ();}}
When to use the combined mode
Quote a fragment of the big Talk design pattern: "When you discover that a requirement is a part and a whole hierarchy, and you want users to be able to ignore the difference between a combined object and a single object, you should consider combining patterns when you use all the objects in a composite structure uniformly." "
Java design mode (10): Structured-combined mode (Composite)