The Xiangyuan mode is different from the general design mode. It is mainly used to optimize the performance of the program. It is best to solve the performance problems caused by a large number of similar objects. The Encyclopedia pattern reduces the number of objects and thus improves the performance of the application by analyzing the application's objects and parsing them into intrinsic and external data.
Basic knowledge
The Encyclopedia mode reduces the number of objects by sharing a large number of fine-grained objects, thereby reducing the memory of objects and improving the performance of applications. The basic idea is to decompose the composition of existing similar objects and expand them into shared internal data and non-shared external data. We call the object of the internal data a meta object. Usually a factory class is also needed to maintain intrinsic data.
In JS, the Encyclopedia mode mainly consists of the following characters:
(1) Client: a class used to call the Xiangyuan factory to obtain intrinsic data, usually the object required by the application.
(2) Xiangyuan Factory: Class used to maintain Xiangyuan Data
(3) Enjoy the Yuan class: a class that maintains internal data
Implementation and application of Xiangyuan mode
General implementation
Let’s give an example to illustrate: Apple mass-produces iPhones. Most of the data such as models and screens are the same, and a few parts of the data such as memory are divided into 16G, 32G, etc. Before using the Encyclopedia mode, we write the code as follows:
function Iphone(model, screen, memory, SN) { this. model = model; this.screen = screen; this.memory = memory; this.SN = SN;}var phones = [];for (var i = 0; i < 1000000; i++) { var memory = i % 2 == 0 ? 16 : 32; phones.push(new Iphone("iphone6s", 5.0, memory, i));}In this code, one million iPhones are created, and each iPhone applies for one memory independently. But when we look closely, we can see that most iPhones are similar, except that the memory and serial numbers are different. If it is a program with high performance requirements, we must consider optimizing it.
For a large number of programs with similar objects, we can consider using the Xiangyuan mode to optimize it. We analyze that most iPhone models, screens, and memory are the same, so this part of the data can be used for public purposes, which is the internal data in the Xiangyuan mode. The definition of the Xiangyuan class is as follows:
function IphoneFlyweight(model, screen, memory) { this.model = model; this.screen = screen; this.memory = memory;}We define the Enjoy class of iPhone, which contains three data: model, screen and memory. We also need a Xiangyuan factory to maintain this data:
var flyweightFactory = (function () { var iPhones = {}; return { get: function (model, screen, memory) { var key = model + screen + memory; if (!iphones[key]) { iPhones[key] = new IphoneFlyweight(model, screen, memory); } return iPhones[key]; } };})();In this factory, we define a dictionary to save the sacrificial object, provide a method to obtain the sacrificial object according to the parameters, and if there is a sacrificial, it will be returned directly, and if there is no sacrificial, it will be created.
Next we create a client class, which is modified from the iPhone class:
function Iphone(model, screen, memory, SN) { this.flyweight = flyweightFactory.get(model, screen, memory); this.SN = SN;}Then we still generate multiple iPhones as in between
var phones = [];for (var i = 0; i < 1000000; i++) { var memory = i % 2 == 0 ? 16 : 32; phones.push(new Iphone("iphone6s", 5.0, memory, i));}console.log(phones);The key here is this.flyweight = flyweightFactory.get(model, screen, memory) in the Iphone constructor. This code obtains Xiangyuan data through the Xiangyuan factory. In the Xiangyuan factory, if an object with the same data already exists, it will directly return the object. Multiple iPhone objects share this part of the same data, so the original similar data has been greatly reduced, reducing memory usage.
Application of Enjoy the Yuan mode in DOM
A typical application of the Xiangyuan mode is DOM event operation, and the DOM event mechanism is divided into event bubbles and event capture. Let's briefly introduce these two:
Event Bubble: The bound event starts from the innermost element and then bubbles to the outermost layer
Event capture: The bound event starts from the outermost element and then passes to the innermost layer.
Suppose we have a menu list in HTML
<ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</li> <li>Option 4</li> <li>Option 5</li> <li>Option 6</li></ul>
Click the menu item to perform the corresponding operation. We bind events through jQuery, which usually does:
$(".item").on("click", function () { console.log($(this).text());})Bind events for each list item and click to output the corresponding text. There is no problem at this time, but if it is a very long list, especially if it is a mobile phone with a particularly long list, there will be performance problems, because each item is bound to events and takes up memory. But these event handlers are actually very similar, so we need to optimize them.
$(".menu").on("click", ".item", function () { console.log($(this).text());})In this way, the number of event handlers can be reduced. This method is called event delegation, which also uses the principle of the Xiangyuan model. The event handler is a common internal part, and the text of each menu item is an external part. Let’s briefly talk about the principle of event delegation: click on the menu item, and the event will bubble from the li element to the ul element. When we bind the event to ul, we actually bind an event, and then use the target in the event parameter event to determine which element the click is. For example, the first li element at the low level, event.target is li. In this way, we can get the specific click element and we can handle differently according to different elements.
Summarize
The Encyclopedia mode is a means to optimize program performance, and to reduce the number of objects by sharing public data to achieve optimization programs. The Encyclopedia mode is suitable for scenarios where there are a large number of similar objects and performance requirements. Because the Xiangyuan mode needs to separate internal and external data, it increases the logical complexity of the program, it is recommended to use the Xiangyuan mode only when there are performance requirements.
The benefits of Enjoy the Yuan model:
The resource compliance of web pages can be reduced by orders of magnitude. Even if the application of Xiangyuan mode cannot reduce the number of instances to one, you can still benefit a lot from it.
This saving does not require a lot of modification of the original code. After creating the manager, factory and Xiangyuan, the modifications to the code are nothing more than changing from directly instantiating the target class to calling a method of the manager object.
Disadvantages of Enjoy the Yuan mode:
If it is used in unnecessary places, the result will actually damage the running efficiency of the code. This pattern optimizes the code while also increasing its complexity, which can cause difficulties in debugging and maintenance.
It hinders debugging because now there are three possible errors: manager, factory and xiangyuan.
This optimization can also make maintenance more difficult. Now you are not facing a clear architecture composed of objects encapsulating data, but a bunch of messy things. The data in it is saved in at least two places. It is best to comment on the internal data and the external data.
This optimization should only be done when necessary. A trade-off must be made between operational efficiency and maintainability. If you are not sure whether you need to use the Encyclopedia mode, then you most likely don't need it. The Xiangyuan mode is suitable for occasions such as system resources have been used almost and obviously some kind of optimization is needed.
This pattern is especially useful for Javascript programmers because it can be used to reduce the number of DOM elements to be used on a web page, knowing that these elements consume a lot of memory. Using this pattern and organizational type such as combination patterns can develop feature-rich complex web application systems that can run smoothly in any modern Javascript environment.
Applicable occasions for the Xiangyuan mode:
A large number of resource-intensive objects must be used in the web page. If only a few of these objects are used, this kind of optimization is not cost-effective.
At least a portion of the data stored in the object can be converted into external data. Furthermore, storing this data outside the object should take relatively little resources, otherwise this approach is actually meaningless for performance hints. The type of object that contains a large amount of basic code and HTML content may be more suitable for this kind of optimization.
After separating the external data, the number of unique objects is relatively small.