JavaScript design mode-combined mode

Source: Internet
Author: User

The problem to be solved by the combination mode:

You can combine complex objects with simple objects, and this complex object can be combined into larger objects. You can define simple objects as classes and then define some container classes to store these simple objects.

The client code must distinguish between object simple objects and container objects, but in most cases the user thinks they are the same. The difference between these classes makes the program more complex. Recursive use of time with trouble, and how we use recursive combinations,

So that users do not have to distinguish between these classes?

Concept:

Combines objects into a tree structure to represent a "partial-whole" hierarchy. Composite makes the user consistent with the use of individual objects and composite objects.

Sometimes called part-overall mode, it blurs the concept of simple elements and complex elements in the problem of our tree structure, and the client program can deal with complex elements like simple elements, thus decoupling the client program from the internal structure of the complex elements.

The combined mode allows you to optimize the processing of recursive or hierarchical data structures. There are many examples of hierarchical data structures that make combinatorial patterns very useful. A universal example of hierarchical data structures is what you encounter every time you use a computer: the file system. The file system consists of directories and files. Each directory can be loaded with content. The contents of a directory can be either a file or a directory. In this way, the computer's file system is organized in a recursive structure. If you want to describe such a data structure, then you can use the combined mode composite.

Applicable scenarios:

Want to represent the whole-local structure of an object,

You want users to ignore the combination object and the individual object, the user can use all the objects without distinction.

UML diagram:

In JavaScript, the composition pattern is tailor-made for creating a dynamic user interface, because the HTML structure conforms to the structure of the applicable scenario for the combined pattern.

1. There are a number of objects organized into a hierarchical system.

2. You want to implement an operation on this batch of objects or on some of the objects.

The combination mode is good at manipulating large batches of objects, specifically for organizing such object operations from one level down to the next, to weaken the coupling between objects and to use some classes or instances interchangeably. Make your code more modular and easy to maintain.

The following is an example of a picture library in JS design mode:

The first is the constructor of the picture library:

functionImagesstore (ID) { This. Children = [];  This. Element = document.createelement ("div");  This. element.id =ID;  This. Element.classname = "Imgs-store";} Imagesstore.prototype={constructor:imagesstore, add:function(child) { This. Children.push (child);  This. Element.appendchild (Child.getelement ()); }, remove:function(child) { for(varnode, i=0; node = This. Getchild (i); i++ ){           if(node = = =Child ) {                This. Children.splice (I, 1 );  Break; }            This. Element.removechild (Child.getelement ()); }}, Getchild:function(i) {return  This. Children[i]; }, Show:function(){        This. Element.style.display = ";  for(varnode, i=0; node = This. Getchild (i); i++) {node.show (); }}, Hide:function(){         for(varnode, i=0; node = This. Getchild (i); i++) {node.hide (); }        This. Element.style.display = ' None '; }, GetElement:function(){       return  This. Element; }};

As we can see from the combined object above, the hide and show methods on the prototype are not simply processed for the current element, but are also derived to each of its contained leaf objects. This way, the operation mechanism of the combined mode is embodied, and a command fires complex or recursive behavior on multiple objects. Here we can see that the element attribute in each object points to the object's real DOM object, which is generally not a big problem, but it is important to be careful to put the DOM object into the reference JS object's properties, which will lead to memory leaks in some browsers, Some memory cannot be reclaimed.

The following is the constructor for the child node Image:

functionImageitem (src) { This. Element = document.createelement ("img");  This. ELEMENT.SRC =src;  This. Element.classname = "Img-item";} Imageitem.prototype={constructor:imagesstore, add:function(child) {Throw NewError ("This is Image object, no Add function"); }, remove:function(child) {Throw NewError ("This is the image object, no remove function"); }, Getchild:function(i) {Throw NewError ("This is Image object, no Getchild function"); }, Show:function(){         This. Element.style.display = "; }, Hide:function(){         This. Element.style.display = ' None '; }, GetElement:function(){        return  This. Element; }};

It can be seen clearly, for the library node and image child nodes, in addition to the library node support Add\remove\getchild and other structures on the structure of the operation, the other methods and image nodes are not different, and for the upper nodes, will recursively call the corresponding method of the lower node, this is the combination mode to do.
Call:

var New Imagesstore ("First"new imageitem ("/img/1.jpg"New

Inserting store.element in the corresponding DOM can be controlled using the Store.show () method. And the coupling between each object is very loose, and the simple operation deals with complex results.

Objects organized using the composition pattern have a clear hierarchy, which is actually a deep-first node search for the entire structure whenever an operation is performed on the top-level composite object. But these advantages are traded at the expense of the operation, such as the top-level every time the actual operation of the store.show is the entire tree structure of the nodes are traversed to execute once.

The combo mode is to organize a batch of sub-objects into a tree structure, and a top-level command will be all the objects in the action tree. It improves the modularity of the code and is highly adaptable to the Dynamic HTML interface.

JavaScript design mode-combined mode

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.