JS Design Pattern Basics

Source: Internet
Author: User

1. Polymorphism (' Do what ' and ' who to do ' separate)

The same action applies to different objects, which can produce different interpretations and different execution results (for example, different animal sounds). will be separated from the same.

//ObjectvarMakeSound =function(animal) {animal.sound ();}//different OperationsvarDuck =function() {};D uck.prototype.sound=function() {Console.log (' Quack ');}//different behaviors.varChicken =function(){}; Chicken.prototype.sound=function() {Console.log (' Giggle ');} MakeSound (NewDuck ()); MakeSound (NewChicken ());

Use inheritance to get polymorphic effects.  (A sparrow is flying, a magpie is flying) it can be said that a bird is flying. Java uses abstract class inheritance.

Polymorphism and Design Patterns (Command mode, combo mode, policy mode)

2. Encapsulation (more important package changes, separating the unchanging parts from the easily changing ones)

1) package data. 2) package implementation. (iterator, each) 3) package type. 4) package changes.

//Encapsulation Implementationfunction$each (Jn, fn) {varLen =jn.length; if("number" = = =typeofLen) {         for(vari = 0; i < Len; i++) {            Try{fn (jn[i], I,JN); } Catch(e) {if($ Break(e)) { Break; } Else {                    Throwe;            }; }        }    } Else {         for(varKinchJn) {            Try{fn (jn[k], K,JN); } Catch(e) {if($ Break(e)) { Break; } Else {                    Throwe;            }; }        }    }}

3. Cloning.

function (obj) {    varfunction() {};     = obj;     return New F ();}

4. Open-closed principle.

The logic of putting in too much if-else out of the function.

5. Single principle.

JS design mode Basics

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.