During our normal development process, we will definitely encounter this situation: we process 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 the client must maintain consistency when processing them. For example, for product orders in e-commerce websites, each product order may have multiple sub-order combinations, such as folders in the operating system, each folder has multiple sub-folders or files. When we copy, delete them, etc., 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 to achieve it.
Basic knowledge
Combination mode: Combining objects into a tree structure to represent a "part-total" hierarchy. Combination mode allows users to have consistency in their use of individual objects and combined objects.
There are three main characters in the combination mode:
(1) Abstract component (Component): an abstract class that mainly defines the public interface of the objects participating in the combination
(2) Sub-object (Leaf): The most basic object that forms a combined object
(3) Composite: Complex objects combined by child objects
The key to understanding the combination pattern is to understand the consistency of the combination pattern for individual objects and combined objects. Let’s talk about the implementation of combination patterns to deepen our understanding.
Combination mode is tailored to create UI dynamically on the page. You can use only one life= command to initialize some complex or recursive operations for many objects. Combination mode provides two points:
(1) Allow you to treat a group of objects as specific objects. A composite object implements the same operation as the sub-objects that make it. Performing a certain operation on a combined object will cause all sub-objects under that object to perform the same operation. Therefore, you can not only seamlessly replace a single object into a set of objects, but also the same in turn. These independent objects are so-called loosely coupled.
(2) The combination pattern will combine the set of sub-objects into a tree structure and allow traversal of the entire tree. This will hide the internal implementation and allow you to organize the sub-objects in any way. Any code for this object (combined 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 HTML documents is a natural tree structure. The most basic elements become DOM trees and eventually form DOM documents. It is very suitable for combination mode.
We often use jQuery class library, where the combination pattern is applied more frequently, for example, the following code is often implemented:
$(".test").addClass("noTest").remove("test");This simple code is to get the element that class contains test, and then process it with addClass and removeClass. Whether $(".test") is one element or multiple elements, it is ultimately called through the unified addClass and removeClass interfaces.
Let's briefly 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 (compatibility and universality are not considered for the time being), and it is simple to judge the node type first, and then add className according to different types. For NodeList or Node, client calls use the addClass interface the same way. This is the most basic idea of the combination mode, making the use of part and the whole consistent.
(2) Typical examples
We mentioned a typical example: a product order contains multiple product sub-orders, and 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 pattern into 2 roles:
(1) Subobject: In this example, the subobject is a product suborder
(2) Combination object: This is the total order of the product
Suppose we develop a tourism product website that 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 order 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 has three main members: an order list, a method to add an order, and a method to create an order.
When using the client, the following is as follows:
var flight = new FlightOrder();flight.create();var orders = new TotalOrders();orders.addOrder(new FlightOrder());orders.addOrder(new HotelOrder());orders.create();
Client calls show two ways, one is to create air ticket orders, and the other is to create multiple orders, but they are eventually created through the create method. This is a very typical application scenario of the combination mode.
Summarize
The combination pattern is not difficult to understand. It mainly solves the consistency problem of single objects and combined objects in the way they are used. This is great for using combinatorial patterns if objects have obvious hierarchies and want to use them uniformly. In web development, this hierarchy is very common and is very suitable for using combination patterns. Especially for JS, you do not have to stick to the traditional object-oriented language form, and flexibly use the characteristics of JS language to achieve consistency in part and overall use.
(1) Scenarios using combination mode
Use combination mode when encountering the following two situations
A. A collection of objects containing a certain hierarchical structure (the specific structure cannot be determined during the development process)
B. Want to perform some operation on these objects or some of them
(2) Disadvantages of combination mode
Because any operation of a combined object will call the same operation on all sub-objects, there will be performance problems when the combined structure is large. Also, when using the combination mode to encapsulate HTML, you must select the appropriate tag. For example, the table cannot be used in the combination mode, and the leaf nodes are not obvious.