Home > Article > Web Front-end > Common design patterns in JS
In large-scale single-page applications, when the complexity rises to a certain level, there is no appropriate design pattern for decoupling, and subsequent development will be difficult to start.
The design pattern exists precisely for decoupling.
The core of the singleton mode is to ensure that there is only one instance and provide global access.
Satisfies the "Single Responsibility Principle": Use the proxy mode, do not determine whether the singleton has been created in the constructor;
Satisfies the inertia principle
The login window pops up.
var getSingle = function (fn) { var res; return function() { return res || (res = fn.apply(this, arguments)); } } var createPopup() { var p = document.createElement('p'); p.innerHTML = "Login window"; p.style.display = "none"; document.body.appendChild(p); return p; } var createLoginPopup = getSingle(createPopup); //create popup p here by using a given function, 满足两个原则 document.getElementById("loginBt").onclick = function() { var popup = createLoginPopup(); pop.style.display = "block"; }
/** * 构造一个动物的函数 */ function Animal(name, color){ this.name = name; this.color = color; this.getName = function(){ return this.name; } } // 实例一个对象 var cat = new Animal('猫', '白色'); console.log( cat.getName() );
function Person(){ } Person.prototype.name = "bill"; Person.prototype.address = "GuangZhou"; Person.sayName = function (){ alert(this.name); } var person1 = new Person(); var person2 = new Person(); //测试代码 alert(person1.name); // bill alert(person2.name); // bill person1.sayName(); //bill person2.sayName(); //bill person1.name = "666"; alert(person1.name); // 666 alert(person2.name); // bill person1.sayName(); //666 person2.sayName(); //bill
/** * 混合模式 = 原型模式 + 构造函数模式 */ function Animal(name, color){ this.name = name; this.color = color; console.log( this.name + this.color) } Animal.prototype.getInfo = function(){ console.log('名称:'+ this.name); } function largeCat(name, color){ Animal.call(null, name, color); this.color = color; } largeCat.prototype = create(Animal.prototype); function create (parentObj){ function F(){} F.prototype = parentObj; return new F(); }; largeCat.prototype.getColor = function(){ return this.color; } var cat = new largeCat("Persian", "白色"); console.log( cat )
Factory: The function generates the b object internally and returns it.
1. function a(name){ var b = new object(); b.name = name; b.say = function(){ alert(this.name); } return b } 2. function Animal(opts){ var obj = new Object(); obj.name = opts.name; obj.color = opts.color; obj.getInfo = function(){ return '名称:'+obj.name +', 颜色:'+ obj.color; } return obj; } var cat = Animal({name: '波斯猫', color: '白色'}); cat.getInfo();
The idea of the simple factory pattern is to create objects and instantiate different classes; you only need to create an object, and then use a large number of methods and properties of this object, and In the end, the object is returned
//basketball base class var Baseketball = function(){ this.intro = 'baseketball is hotting at unitedstates'; } Baseketball.prototype = { getMember : function(){\ console.log('each team needs five players'); }, getBallSize : function(){ console.log('basketball is big'); } } //football base class var Football = function(){ this.intro = 'football is popular at all of the world'; } Football = function(){ getMember = function(){ }, getBallSize = function(){ } } //sport factory var SportsFactory = function(name){ switch(name){ case 'NBA': return new Baseketball(); case 'wordCup': return new Football(); } } //when you want football var football = SportsFactory('wordCup'); console.log(football); console.log(football.intro); football.getMember();
Decorator pattern
Define algorithms that can be replaced with each other, and They encapsulate.
Conforms to the open-closed principle: When you want to modify the algorithm used, you don’t need to go deep into the function to modify it, you only need to modify the strategy class;
Separate the implementation and use of the algorithm to improve the reusability of the algorithm;
Avoid multiple conditional selection statements through combination, delegation and polymorphism;
animation to achieve different easing effects.
Generally divided into two parts: strategy class and environment class. The strategy class is used to encapsulate various algorithms and is responsible for the specific calculation process; the environment class is responsible for receiving user requests and entrusting the requests to a certain strategy class. Because the algorithms and calculation results implemented by each strategy class are different, but the method of calling the strategy class by the environment class is the same, this reflects polymorphism. To implement different algorithms, you only need to replace the strategy class in the environment class.
In js, we do not have to construct a strategy class and can directly use functions as strategy objects.
Example
var strategies = { "s1": function() { //algo 1 }, "s2": function() { //algo 2 }, "s3": function() { //algo 3 } } var someContext = new SomeConext(); someContext.start("s1"); //using s1 to calculate //someContext.add("s1"); or add s1 as a rule for validation
can also be translated as facade mode. It provides a consistent interface for a set of interfaces in a subsystem. The Facade pattern defines a high-level interface that makes this subsystem easier to use. After the appearance role is introduced, the user only needs to interact directly with the appearance role. The complex relationship between the user and the subsystem is realized by the appearance role, thus reducing the coupling of the system.
For example, if you want to watch a movie at home, you need to turn on the stereo, then turn on the projector, then turn on the player, etc. After introducing the appearance character, you only need to call the "Open Movie Device" method. The appearance role encapsulates operations such as opening the projector, providing users with an easier-to-use method.
Simplify complex interfaces
Decoupling and shielding users from direct access to subsystems
In form, appearance mode looks like this in javascript:
function a(x){ // do something } function b(y){ // do something } function ab( x, y ){ a(x); b(y); }
The following is an example of blocking bubbling and blocking default events. When it comes to the role of appearance:
var N = window.N || {}; N.tools = { stopPropagation : function( e ){ if( e.stopPropagation ){ e.stopPropagation(); }else{ e.cancelBubble = true; } }, preventDefault : function( e ){ if( e.preventDefault ){ e.preventDefault(); }else{ e.returnValue = false; } }, stopEvent : function( e ){ N.tools.stopPropagation( e ); N.tools.preventDefault( e ); }
The application of appearance mode in JavaScript can be mainly divided into two categories. A certain piece of code appears repeatedly. For example, the call of function a basically appears before the call of function b, so you can consider it. Wrap this code with appearance roles to optimize the structure. Another way is to place APIs that are incompatible with some browsers within the appearance for judgment. The best way to deal with these problems is to centralize all cross-browser differences into an appearance mode instance to provide an external interface.
Definition of proxy mode: Provide a proxy for other objects to control access to this object. In some cases, one object is not suitable or cannot directly reference another object, and a proxy object can act as an intermediary between the client and the target object.
Virtual agent delays the creation and execution of some expensive objects until they are really needed
//图片加载 let imageEle = (function(){ let node = document.createElement('img'); document.body.appendChild(node); return { setSrc:function(src){ node.src = src; } } })(); //代理对象 let proxy = (function(){ let img = new Image(); img.onload = function(){ imageEle.setSrc(this.src); }; return { setSrc:function(src){ img.src = src; imageEle.setSrc('loading.gif'); } } })(); proxy.setSrc('example.png');
If there is a function that requires frequent request operations, which is relatively expensive, you can collect request data over a period of time through a proxy function and issue it all at once
//上传请求 let upload = function(ids){ $.ajax({ data: { id:ids } }) } //代理合并请求 let proxy = (function(){ let cache = [], timer = null; return function(id){ cache[cache.length] = id; if(timer) return false; timer = setTimeout(function(){ upload(cache.join(',')); clearTimeout(timer); timer = null; cache = []; },2000); } })(); // 绑定点击事件 let checkbox = document.getElementsByTagName( "input" ); for(var i= 0, c; c = checkbox[i++];){ c.onclick = function(){ if(this.checked === true){ proxy(this.id); } } }
The cache proxy can provide temporary storage for some expensive operation results. During the next operation, if the parameters passed in are consistent with the previous ones, the previously stored operation results can be directly returned
//计算乘积 let mult = function(){ let result = 1; for(let i = 0,len = arguments.length;i < len;i++){ result*= arguments[i]; } return result; } //缓存代理 let proxy = (function(){ let cache = {}; reutrn function(){ let args = Array.prototype.join.call(arguments,','); if(args in cache){ return cache[args]; } return cache[args] = mult.apply(this,arguments); } })();
1. Advantages: The proxy mode can separate the proxy object from the called object, reducing the coupling of the system. The proxy mode plays an intermediary role between the client and the target object, which can protect the target object. The proxy object can also perform other operations before calling the target object.
2. Disadvantages: Increases the complexity of the system
Observer mode
/** * 模块模式 = 封装大部分代码,只暴露必需接口 */ var Car = (function(){ var name = '法拉利'; function sayName(){ console.log( name ); } function getColor(name){ console.log( name ); } return { name: sayName, color: getColor } })(); Car.name(); Car.color('红色');
Related recommendations:
JS combination design pattern detailed explanation
Detailed Explanation of the Service Locator Pattern Example of PHP Design Pattern
Detailed Explanation of the Delegation Pattern of PHP Design Pattern
The above is the detailed content of Common design patterns in JS. For more information, please follow other related articles on the PHP Chinese website!