JS pit design patterns

The purpose of design patterns

  In order to optimize the code, optimize memory, code reuse, efficient solve some problems, a summary of some programming experience.

Singleton

  Scenario: When you create a duplicate of a higher target. In order to optimize the code, save memory. Single embodiment, it is determined whether the object has been generated, if generated, new new objects already have returned.

  The classic way to achieve is to create a class, or a function, class or function contains a method that without the presence of an object, will create a new instance of the object. If the object exists, this method simply returns the object. 

Single = var (function () { 
    var instance; 
    function the init () { 
        // private methods and properties defined 
        // logical operations 
        return { 
           // public methods and properties defined 
        }; 
    } 
    return { 
        // Get Example 
        getInstance: function () { 
            IF (instance!) { 
                instance = the init (); 
            } 
            return instance; 
        } 
    } 
}) (); // this function must be performed anonymously. I do not know why 

var obj1 = Single.getInstance (); 
var obj2 = Single.getInstance (); 
console.log (=== obj1 obj2);

  Factory mode ----

  A plurality of multiple instances of like high, a class may be packaged, produced by different instances of mass participation.

  Many relationship, a factory, a class, passing different parameters to obtain different instances.

Factory pattern is most commonly used to instantiate the object model, a model is in place with a new plant operating method.

Because the factory mode is equivalent to creating a new instance of an object, we often generated according to Class class instance object, such as A a = new A () is used to create an instance of the factory model objects, since it is necessary when a plurality of new eye, consider whether you can use the factory pattern, although doing so may be a bit more work, but will give you greater system scalability and the amount of modifying as little as possible.

Animal function (the opts) { 
    var obj = new new Object (); 
    obj.color = opts.color; 
    obj.name = opts.name; 
    obj.getInfo = function () { 
        return 'Name:' + obj.name + ', color : '+ obj.color; 
    } 
    return obj; 
} 
var Animal CAT = ({name:' Persian ', color:' white '}); 
cat.getInfo (); 
var = Animal Dog ({name:' mangy dog ' , color: 'black'}); 
dog.getInfo (); 

// here why. Only one instance of the data printed out of it?

Constructor mode

 Constructors in ECMAScript can be used to create specific types of objects, such as Array and Object native constructor at runtime will automatically appear in the execution environment. Further, a constructor can also create custom properties and methods to define custom objects. The method of using the constructor, not only solves the problem of repeated instances of, and solve the problem of object recognition.

Animal function (name, Color) { 
    this.name = name; 
    this.color = Color; 
    this.getName = function () { 
        return this.name; 
    } 
} 
// instance of an object 
var cat = new Animal ( 'cat', 'white'); 
the console.log (cat.getName ());

  The observer pattern | publish / subscribe mode (subscribe & publish) the two are different, the observer mode is the base mode, the subscription release mode, a minor upgrade. Or one to many relationship. It is a

text attributes changed, set the trigger method, but does not change the content of the text node. How can the same be bound to text text nodes can also synchronize changes? Here is one more point of knowledge: Subscribe release mode.
  Subscribe to release mode, also known as the observer mode, defines the relationship of one to many, so that multiple observers simultaneously monitor a particular theme object, you'll notice all the objects observer state the subject object changes.
Posted by notice => Themes objects notified and pushed to subscribers => subscribers appropriate action.
  

// publisher a publisher, news function is responsible for the release - publish 
        var = {Pub 
            publish: function () { 
                dep.notify (); 
            } 
        } 
        // multiple subscribers subscribers, execute the function after the publisher publishes a message 
        var sub1 {= 
            Update: function () { 
                the console.log (. 1); 
            } 
        } 
        var {SUB2 = 
            Update: function () { 
                the console.log (2); 
            } 
        } 
        var {SUB3 = 
            Update: function () { 
                the console.log ( . 3); 
            } 
        }  
        // a topic objects
        function Dep () {
            = this.subs [SUB1, SUB2, SUB3]; 
        } 
        Dep.prototype.notify = function () { 
            this.subs.forEach (function (Sub) { 
                sub.update (); 
            }); 
        } 

        // publishers publish messages theme object performs notify method, which triggers subscribe to execute the Update method 
        var = new new DEP Dep (); 
        pub.publish ();

  Publishers are responsible for publishing information, the subscriber receives a message is responsible for receiving, but the most important is the theme of the object message, he needs to record all subscribers of this news special person, then it is responsible for publishing the notice to which people subscribe to the news.

----- combination pattern-many relationship, a class or method, batch processing everything.

Combination pattern may be described as a group of objects treated as a single object.

This allows us to deal with a unified single object or multiple objects. This means either an object or one thousand objects we can to deal with the same behavior.

In Jquery, when we apply the method in a node or nodes, in the same way we can select the object and returns JQuery.

The following presentation we will use Jquery selectors. A set of elements to a single element (such as element has a unique ID), or have the same label, or add the class named Class of active, treat them using the no different:

// 单一节点
$( "#singleItem" ).addClass( "active" );
$( "#container" ).addClass( "active" );

// 一组节点
$( "div" ).addClass( "active" );
$( ".item" ).addClass( "active" );
$( "input" ).addClass( "active" );

  The JQuery. AddClass () implemented directly used for the native loop, Jquery the JQuery.each (), Jquery.fn.each to iterate over a collection in order to achieve simultaneously a process or a group of elements. Consider the following example:

addClass: function( value ) {
  var classNames, i, l, elem,
    setClass, c, cl;

  if ( jQuery.isFunction( value ) ) {
    return this.each(function( j ) {
      jQuery( this ).addClass( value.call(this, j, this.className) );
    });
  }

  if ( value && typeof value === "string" ) {
    classNames = value.split( rspace );

    for ( i = 0, l = this.length; i < l; i++ ) {
      elem = this[ i ];

      if ( elem.nodeType === 1 ) {
        if ( !elem.className && classNames.length === 1 ) {
          elem.className = value;

        } else {
          setClass = " " + elem.className + " ";

          for ( c = 0, cl = classNames.length; c < cl; c++ ) {
            if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
              setClass += classNames[ c ] + " ";
            }
          }
          elem.className = jQuery.trim( setClass );
        }
      }
    }
  }

  return this;
}

  In summary, 23 kinds of classification models, too pit, and the lack of specific classification criteria, and the name of the mode of play is a mess, not too literally. This is a very disgusting place. Also you need a lot of exposure to different projects, to learn from him.

Guess you like

Origin www.cnblogs.com/cn-oldboy/p/12355180.html