First, the combination pattern definition and the use scene
Combined mode combines objects into a tree structure to represent the "partial-whole" hierarchy, which, in addition to representing the tree structure, can also take advantage of the polymorphism of the object, making the user consistent with the use of individual objects and composite objects.
Key to implementing the combined pattern:
In static languages such as Java, it is necessary to implement the same abstract interface for both a single object and a composite object, which can be implemented by an abstract class or interface.
In JavaScript, the polymorphism of the object is innate, there is no compiler to check the object type, so the key to implementing the composition pattern is to ensure that the combination of cashing a single object UF the same method, which usually requires the use of "duck type" of the idea to interface check them.
Two, combination mode application Case-Scan folder
//Learning in Combinatorial mode: Scanning foldersvarFolder=function (name) { This. name=name; This. files=[];}; Folder.prototype.add=function (file) { This. Files.push (file);}; Folder.prototype.scan=function () {Console.log ('To start scanning folders:'+ This. Name); for(varI=0, len= This. files.length;i<len;i++){ This. Files[i].scan (); }};varfile=function (name) { This. name=name;}; File.prototype.add=function () {Throw NewError ('File cannot be added under file! ');}; File.prototype.scan=function () {Console.log ('To start scanning files:'+ This. name);};//Testvarfolder1=NewFolder ('Technical Books');varfile1=NewFile ('The essence of Javascipt technology'); Folder1.add (file1);varFolder2=NewFolder ('Literature Books');varFile2=NewFile ('See the United States at close range'); Folder2.add (file2);varfile3=NewFile ('The Secrets of Pets');varFolder=NewFolder ('Total Folder'); Folder.add (Folder1); Folder.add (Folder2); Folder.add (file3); Folder.scan ();
JavaScript Design Pattern Learning ten--combination mode