1. Template Method mode
Template method is to abstract multiple models into one, to take out a most basic template, of course, this template can be used as an entity object can also be used as abstract objects, to see your specific requirements, other modules only need to inherit this module method, can also extend this method.
Example: 1, the shape of the cake is the same, are made of cake molds, the reason the cake in the shop looks different, in fact, are in this basis two times, so we added different materials.
2, such as a different prompt box, the basic frame is a prompt box, but the title prompt box more than a title, cancel the prompt box more than a Cancel button and so on.
The core of the template method is the reuse of the method, which is encapsulated in the base class with the new method, and the subclass inherits the method of the base class, realizes the sharing of the base class method, and achieves the common use of the method.
2. Observer mode
Observer pattern: also known as the publish-subscriber pattern or message mechanism, defines a dependency relationship that solves the coupling between the principal object and the Observer's function.
varObserver= (function(){ //prevents Message Queuing from being tampered with and keeps the message container as a static private variable var_messages={}; return { //The registration information interface, which pushes subscribers ' registered messages into the message pair columnRegist:function(TYPE,FN) {if(typeof_messages[type]=== ' undefined ') {_messages[type]=[FN]; }Else{ //pushes an action method into the action execution sequence corresponding to the message_messages[type].push (FN); } }, //Publish Message InterfaceFire:function(Type,args) {//If the message is not registered, it returns if(!_messages[type])return; varevents={type:type, Args:args||{}}, I=0, Len=_messages[type].length; for(; i<len;i++){ //executes the registered message corresponding to the action sequence_messages[type][i].call ( This, events); } }, //removing a message interfaceRemovefunction(TYPE,FN) {if(_messages[type]instanceofArray) { varI=_messages[type].length-1; for(; i>=0;i--){ //If the action exists, the action is removed_MESSAGES[TYPE][I]===FN && _messages[type].splice (i,1); } } } } })();
Since you choose to use observer mode to solve the problem, it is important to first analyze which modules should register the message and which modules should publish the message .
3. State mode
State mode: When an object's internal state changes, it causes its behavior to change, which looks like it has changed the object.
Example: For example, we voted, we have determined that there are several states, if we adopt if,else, this will be repeated judgment, inefficient, and not easy to manage. This is after we can encapsulate different judgment results within a state object, and then the status object returns a callable interface method that is used to invoke some method within the state.
varresult=function(){ //The result of the decision is saved in the internal state varstates={ //Each state is saved as a separate methodSTATE0:function() {}, State1:function() {}, State1:function(){} } //get a state and execute its corresponding method functionShow (Result) {states[' state ' +result] && states["state" +result] (); } return { //Returns the call-to- state method InterfaceShow:show}} ();
There is also a classic example of the game we often play, that is, Super Marie. Mary to jump, but also to shoot, run, etc., we can not use if else to make judgments, the cost of the increase is unimaginable.
varMarrystate=function(){ //The result of the decision is saved in the internal state varstates={ //Each state is saved as a separate methodMovefunction() {}, Jump:function() {}, Shoot:function(){} } }; varaction={changestate:function(){ //The combination is implemented by passing multiple parameters vararg=arguments; //Resetting the internal state_currentstate={}; //add an action if there is an action if(arg.length) {//Traversal Action for(vari=0,len=arg.length;i<len;i++){ //add an action to an internal state_currentstate[arg[i]]=true; } } //easy to chain-call return This; }, goes:function{ //traverse an internal saved action for(varIinch_currentstate) { //action exists then executestates[i]&&States[i] (); } return This; } return { //Returns the call-to- state method InterfaceChange:Action.change, Goes:Action.goes}}; //Create an instance varmarry=Newmarrystate (); Marry. Change ("Jump", "shoot"). goes (). goes (). Change ("Shoot"). goes ();4. Strategy mode
policy mode: encapsulates a defined set of algorithms so that they can be replaced with one another. The encapsulated algorithm has some independence and does not change with the client.
Example : What would you do if you were a merchant and would sell your merchandise for different discounts on different festivals? Using state mode? No, the state mode is for an object, that is, different products you have to write a different state.
The strategy model is more reasonable for the promotion strategy of one item only in one case, without any other promotion strategy.
The same point: structurally, like the state pattern, is also an internal encapsulation of an object, and then through the returned interface implementation of the internal object calls;
different points: The policy mode does not need to manage state, there is no dependency between States, the policy can be replaced with each other, and within the policy object is a separate algorithm.
varPricestate=function(){ //Internal Algorithm Object varstates={return30:function(Price) {}, Return50:function(Price) {}, Pecent80:function(Price) {}, Pecent60:function(Price) {}}//Policy algorithm Call interface return function(algorithm,price) {//If the algorithm exists, the calling algorithm returnstates[algorithm]&&States[algorithm] (price)}};
Similarly, form validation can also be written in a similar form:
varInputstate=function(){ //Internal Algorithm Object varstates={notnull:function(value) {}, Number:function(value) {}, Phone:function(value) {},}//Policy algorithm Call interface return{check:function(type,value) {value=value.replace (/^\s+|\s+$/g, ""); returnstates[type]&&States[type] (value); }, Addstate:function(TYPE,FN) {States[type]=fn; } } };
But in the end we added an interface for adding policy algorithms to the policy object, so that if we had a new policy object, we would just have to add it through the Addstate method without modifying the internal code.
5, responsibility chain mode; 6, Command mode
(Specific reading)
7. Visitor Mode
Visitor Pattern: for elements in an object structure, define a new way to access elements in the structure without changing the object. That is, when you do not change the operation of the object, add a new operation method for him, to achieve access to the Operation object.
As an example: in fact, we can add an array of objects to the operation method: for example, Pop,push.
JS Design Pattern Summary 3