A tutorial on the use of combinatorial patterns in the development of JavaScript design Patterns _ Basics

Source: Internet
Author: User
Tags ticket

In our usual development process, we will certainly encounter this situation: while dealing with simple objects and complex objects composed of simple objects, these simple objects and complex objects will be grouped into a tree structure, when the client to its processing to maintain consistency. For example, the product order in the electricity merchant website, each product order may have multiple child order combinations, such as operating system folders, each folder has multiple subfolders or files, we as a user to copy, delete and other operations, whether it is a folder or file, for our operator is the same. In this scenario, it is very appropriate to use the combination mode for implementation.

Basic knowledge

Combination mode: The grouping of objects into a tree structure to represent a "partial-whole" hierarchy, which makes the user consistent in the use of individual objects and composite objects.
The combination mode has three main roles:
(1) abstract component (Component): abstract class, which mainly defines the public interface of the object participating in the combination
(2) Child object (Leaf): The most basic object that makes up a grouped object
(3) grouped objects (composite): Complex objects grouped by child objects
The key to understanding the combinatorial pattern is to understand the consistency of the combined patterns on the use of individual objects and composite objects, and then we'll talk about the realization of the combinatorial pattern.
Combined mode is designed for dynamically creating a UI on a page, you can use only one Life = command to initialize some complex or recursive operations for many objects. The combination mode provides two of a kind:
(1) allows you to treat a group of objects as a specific object. The combined object (A composite) implements the same operation as the child objects that make up it. Performing an operation on a grouped object will cause all child objects under that object to perform the same operation. So you can not only seamlessly replace a single object with a set of objects, The converse is the same. These independent objects are loosely coupled.
(2) Combination mode combines the set of child objects into a tree structure and allows you to traverse the entire tree. This hides the internal implementation and allows you to organize child objects in any way. Any code for this object (the grouped object) will not depend on the implementation of the inner child object.

The implementation of combinatorial mode

(1) The simplest combination mode

The DOM structure of HTML documents is a natural tree structure, the most basic elements drunk into the DOM tree, the final form of the DOM document, very suitable for the combination mode.
Our common jquery class libraries, where the combination pattern is applied more frequently, for example, often with the following code implementations:

$ (". Test"). AddClass ("Notest"). Remove ("test");

The simple code is to get the element that class contains test, and then do addclass and removeclass processing, regardless of whether $ (". Test") is an element or multiple elements, Ultimately, they are invoked through a unified addclass and Removeclass interface.
Let's simply simulate the implementation of AddClass:

var addclass = function (Eles, className) {
  if (eles instanceof nodelist) {
    for (var i = 0, length = eles.length; i < length; i++) {
      Eles[i].nodetype = = 1 && (eles[i].classname + = (' + className + ')
    }
  }
  else if (eles instanceof Node) {
    Eles.nodetype = = 1 && (eles.classname + = (' + className + '));
  }
  else {
    throw ' eles is not a HTML node ';
  }
}
AddClass (document.getElementById ("Div3"), "test");
AddClass (Document.queryselectorall (". Div"), "test");

This code simply simulates the implementation of addclass (regardless of compatibility and versatility), simply determines the node type and then adds classname based on different types. For nodelist or node, the client invocation uses the same AddClass interface, which is the most basic idea of the combinatorial pattern, which is consistent with the use of parts and the whole.

(2) Typical examples

We mentioned a typical example: the product order contains multiple product sub orders, and multiple product orders form a complex product order. Because of the nature of the JavaScript language, we reduced the three roles of the combined pattern to 2 roles:
(1) Child object: In this example, the child object is the product child order
(2) Combination object: This is the product's total order
Suppose we develop a travel product website that includes airfare and hotel two seed products, we define the following child objects:

function Flightorder () {}
FlightOrder.prototyp.create = function () {
  Console.log ("Flight order created");
function Hotelorder () {}
HotelOrder.prototype.create = function () {
  Console.log ("Hotel order created");
}

The code above defines two classes: the Ticket Order class and the hotel order class, each with its own order creation method.
Next we create a total order class:

function Totalorders () {
  this.orderlist = [];
}
TotalOrders.prototype.addOrder = function (order) {
  this.orderList.push (order);
}
TotalOrders.prototype.create = function (order) {
  for (var i = 0, length = this.orderList.length i < length; i++) {
    this.orderlist[i].create ();
  }
}

This object has 3 main members: The order list, the method to add the order, and the method to create the order.
When used by the client is as follows:

var flight = new Flightorder ();
Flight.create ();

var orders = new Totalorders ();
Orders.addorder (New Flightorder ());
Orders.addorder (New Hotelorder ());
Orders.create ();

Client invocation shows two ways, one is to create a single ticket, one is to create multiple orders, but ultimately through the Create method is created, this is a very typical combination of the application scenario.

The

summary
combination mode is not difficult to understand, and it mainly addresses the problem of consistency of the use of single objects and grouped objects. If objects have a distinct hierarchy and want to use them uniformly, this is a good fit to use a combination pattern. In the Web development, this kind of hierarchy is very common, it is suitable to use the combination mode, especially for JS, do not adhere to the traditional object-oriented language form, flexible use of the characteristics of JS language, to achieve the partial and overall use of consistency.
(1) A scene with a combined pattern
uses the combination mode
A when it encounters the following two situations. A collection of objects containing a hierarchy (the structure cannot be determined during development)
B. You want to perform some action on these objects or some of them.
(2) combination mode disadvantage
because any operation of a grouped object invokes the same operation on all child objects, there is a performance problem when the composition is large. There is also the use of composite mode to encapsulate HTML to select the appropriate label, such as table can not be used in combination mode, leaf nodes are not obvious

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.