Home >Web Front-end >JS Tutorial >Tutorial on the use of combination patterns in JavaScript design pattern development (advanced)

Tutorial on the use of combination patterns in JavaScript design pattern development (advanced)

亚连
亚连Original
2018-05-21 14:06:361699browse

The combination mode can be understood as a tree structure, so the combination mode is suitable for operating a large number of objects, especially those with clear hierarchies. Let's take a look at the tutorial on using the combination mode in the development of the so-called object-oriented JavaScript design mode

In our usual development process, we will definitely encounter this situation: processing simple objects and complex objects composed of simple objects at the same time. These simple objects and complex objects will be combined into a tree structure, and they will be processed on the client. Be consistent when handling. For example, for product orders on e-commerce websites, each product order may have multiple sub-order combinations, such as operating system folders. Each folder has multiple sub-folders or files. As a user, we can copy, delete, etc. When operating, whether it is a folder or a file, it is the same for us operators. In this scenario, it is very suitable to use the combination mode.

Basic knowledge

Combining mode: Combining objects into a tree structure to represent the "part-whole" hierarchy, the combination mode allows users to combine single objects and combinations Objects are used consistently.
The combination mode mainly has three roles:
(1) Abstract component (Component): abstract class, which mainly defines the public interface of the objects participating in the combination
(2) Sub-object (Leaf): forms the combined object The most basic object
(3) Composite object (Composite): a complex object composed of sub-objects
The key to understanding the combination mode is to understand the consistency of the combination mode's use of single objects and combined objects. Let's next Let’s talk about the implementation of the combination model to deepen our understanding.
The combination mode is tailor-made for dynamically creating UI on the page. You can use only one command = to initialize some complex or recursive operations for many objects. The combination mode provides two advantages:
(1 ) allows you to treat a group of objects as a specific object. A composite object (A composite) performs the same operation as the sub-objects that make up it. Performing an operation on the composite object will cause all sub-objects under the object to perform the same operation. .So you can not only seamlessly replace a single object with a set of objects, but also vice versa. These independent objects are so-called loosely coupled.
(2) The combination mode will combine the sub-object sets into a tree structure and allows traversing the entire tree. This hides the internal implementation and allows you to organize the sub-objects in any way. Any code in this object (composite object) will not depend on the implementation of the internal sub-objects.

Implementation of combination mode

(1) The simplest combination mode

The DOM structure of the HTML document is a natural tree structure, the most basic element It is transformed into a DOM tree and finally a DOM document, which is very suitable for the combination mode.
We commonly use the jQuery class library, in which the combination mode is even more frequently used. For example, the following code is often implemented:

$(".test").addClass("noTest").remove("test");

This simple code is to get the element whose class contains test, and then addClass and removeClass processing, whether $(".test") is one element or multiple elements, is ultimately called through the unified addClass and removeClass interfaces.
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 += (&#39; &#39; + className + &#39; &#39;));
    }
  }
  else if (eles instanceof Node) {
    eles.nodeType === 1 && (eles.className += (&#39; &#39; + className + &#39; &#39;));
  }
  else {
    throw "eles is not a html node";
  }
}
addClass(document.getElementById("p3"), "test");
addClass(document.querySelectorAll(".p"), "test");

This code simply simulates the implementation of addClass (not considering compatibility and versatility for the time being). It simply determines the node type first, and then based on different Type adds className. For NodeList or Node, client calls all use the addClass interface. This is the most basic idea of ​​the combination mode, making the use of parts and the whole consistent.

(2) Typical example

We mentioned a typical example earlier: a product order contains multiple product sub-orders, multiple Product sub-orders form a complex product order. Due to the characteristics of the Javascript language, we simplify the three roles of the combination mode into two roles:
(1) Sub-object: In this example, the sub-object is the product sub-order
(2) Combination object: here It is the total order of the product
Suppose we develop a travel product website, which contains two sub-products: air tickets and hotels. We define the sub-objects as follows:

function FlightOrder() { }
FlightOrder.prototyp.create = function () {
  console.log("flight order created");
}
function HotelOrder() { }
HotelOrder.prototype.create = function () {
  console.log("hotel order created");
}

The above code defines two classes: air ticket orders class and hotel order class, each class has 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 mainly has three members: order list, method of adding orders, and method of creating orders.
When used on the client side, it is as follows:

var flight = new FlightOrder();
flight.create();

var orders = new TotalOrders();
orders.addOrder(new FlightOrder());
orders.addOrder(new HotelOrder());
orders.create();

The client call shows two methods, one is to create a single ticket order, and the other is to create multiple orders, but in the end both are through create Method to create, this is a very typical application scenario of the combination mode.

SummaryThe combination mode is not difficult to understand. It mainly solves the problem of consistency in the use of single objects and combined objects. This is a good candidate for using the Composite pattern if your objects have a clear hierarchical structure and you want to work with them uniformly. In Web development, this kind of hierarchical structure is very common, and it is very suitable for using the combination mode, especially for JS. There is no need to stick to the form of traditional object-oriented languages, and the characteristics of the JS language can be flexibly used to achieve partial and overall use. consistency.
(1) Scenarios for using combination modeUse combination mode only when encountering the following two situations
A. A collection of objects containing a certain hierarchical structure (the specific structure is in the development process Unable to determine)
B. Hope to perform some operation on these objects or some of them
(2) Disadvantages of the combination modeBecause any operation on the combined object will affect all sub-objects Calls the same operation, so there will be performance issues when the combined structure is large. Also, when using combined mode to encapsulate HTML, you must choose appropriate tags. For example, table cannot be used in combined mode, and the leaf nodes are not obvious

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The application of the facade appearance pattern in design patterns in JavaScript development (advanced)

Detailed explanation in Methods to implement the adapter pattern in design patterns in JavaScript (graphic tutorial)

Summary of the application of the Adapter adapter pattern in JavaScript design pattern programming (graphic tutorial)

The above is the detailed content of Tutorial on the use of combination patterns in JavaScript design pattern development (advanced). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn