JS design mode

Source: Internet
Author: User

1. Interface

-Interface is one of the most useful tools in an object-oriented JavaScript Programmer's toolbox, so there is no concept of interface defined for JavaScript,

We create interfaces in JavaScript by simulating high-level programming languages.

-The concept of an interface: Provides a means to illustrate what methods an object should have.

-There are typically three ways to build JavaScript interfaces:

-1. Comment Description Interface

    

<script type= "Text/javascript" charset= "Utf-8" >//in JavaScript, there are three ways of defining an interface            //1. Note Description (features, 1. Programmers can have a reference, 2 The disadvantage is still belong to the document category, 3 if the programmer forgot to define the method, no error. )            //disadvantage, the way is too loose, and does not check whether the interface mode is fully implemented.             /** * Interface Composite {* * function add ();             * function remove ();             * function Update (); * }             */            //Compositimpl implements Composite            varCompositimpl =function () {                            }; //a prototype object, written directly in the class, creates the method several times. CompositeImpl.prototype.add =function(obj) {//Do something            }; CompositeImpl.prototype.remove=function(obj) {//Do something            }; CompositeImpl.prototype.update=function(obj) {//Do something            }; </script>

-2. Attribute Detection interface

<script type= "Text/javascript" charset= "Utf-8" >//2. Attribute Detection            /** * Interface Composite {* * function add ();             * function remove ();             * function Update ();             *} * * Interface FormItem {* Function select (obj); * }             */                        //Compositimpl implements Coposite and FormItem            varCompositimpl =function (){                //The interface that is displayed inside the class that accepts the implementation                //in general, define a variable inside the class, and the name should be fixed. This is a specification                 This. implemtnsinterface = [' Comosite ', ' FormItem '];                        }; CompositeImpl.prototype.add=function(obj) {//Do somethingAlert (' Add ');                        }; CompositeImpl.prototype.remove=function(obj) {//Do somethingAlert (' Remove ');                        }; CompositeImpl.prototype.update=function(obj) {//Do somethingAlert (' Update ');                        }; CompositeImpl.prototype.select=function(obj) {//Do somethingAlert (' SELECT ');                        }; //define a method to detect if the class implements all interfaces            functionCheckcompositimpl () {//determines whether the current object implements all interfaces                if(! Isimplments (instance, ' Composite ', ' FormItem ')) {                    Throw NewError (' Object does not implement a required interface '); }            }                        //determines whether the current object implements all interfaces            //The main purpose of this method is to determine if an instance object has an interface that implements the relevant            functionisimplments (Object) {//arguments getting the actual parameters                 for(vari = 1; i < arguments.length; i++) {                    //accept the name of each interface that is implemented                    varInterfacenmae =Arguments[i]; varInterfacefound =false;  for(varg = 0; G < Object.implemtnsInterface.length; g++) {                        if(Object.implemtnsinterface[g] = =InterfaceName) {Interfacefound=true;  Break; }                    }                                        if(!iterfacename) {                        return false; }                }                return true; }        </script>

-3. Duck Type Distinguishing interface

<script type= "Text/javascript" charset= "Utf-8" >//3. Duck type identification (the most perfect way to implement the interface)            //Core: The primary purpose of a class implementation interface is to implement all the methods in the interface. (detection method)            //Pros: Fully object-oriented, code is unified, also realizes decoupling                                    //1. Interface Classes class Interface ==> instantiate n multiple interfaces                        /** Interface class requires two parameters * 1. The name of the interface * 2. An array of accepted method names*/            varInterface =function(name, methods) {//1. Determine the number of parameters for the interface                if(Arguments.length! = 2) {                    Throw NewError (' This instance interface constructor must is 2 length '); }                 This. Name =name; //defines a built-in empty array, waiting to accept elements inside the methods                 This. Methods = [];  for(vari = 0, len = methods.length; i < Len; i++) {                    if(typeofMethods[i]!== ' string ') {                        Throw NewError (' The interface method name is error! '); }                     This. Methods.push (Methods[i]);                                    }            }; //2. Preparatory work: Specific implementation classes            //instantiating an interface object            varCompositeinterface =NewInterface (' Compositeinterface ', [' Add ', ' remove ']); varFormiteminterface =NewInterface (' Formiteminterface ', ' Update ', ' SELECT '); //Compositimpl implements Compositeinterface and Formiteminterface.            varCompositimpl =function() {                            }; CompositeImpl.prototype.add=function(obj) {//Do somethingAlert (' Add ');                        }; CompositeImpl.prototype.remove=function(obj) {//Do somethingAlert (' Remove ');                        }; CompositeImpl.prototype.update=function(obj) {//Do somethingAlert (' Update ');                        }; CompositeImpl.prototype.select=function(obj) {//Do somethingAlert (' SELECT ');                         }; //3. Test the method in the interface            //If the test passes, no processing is done. If not passed, the browser throws an exception            //The purpose of this method is to test the methodInterface.ensureimplments =function(Object) {if(Arguments.length < 2) {                    Throw NewError (' Interface.ensureimplments method constructor arguments must be >= 2 '); }                                //obtaining an interface instance object                 for(vari = 1; i < arguments.length; i++) {                    varInstanceinterface =Arguments[i]; //determine if the parameter is the type of the interface class                    if(Instanceinterface.constructor!==interface) {                        Throw NewError (' The arguments constructor not being Interface class! '); }                    //each method in the Loop interface instance Object                     for(varj = 0; J < InstanceInterface.methods.length; J + +) {                        //use a temporary variable to accept the name of each method (string)                        varMethodName =Instanceinterface.methods[j]; if(! Object[methodname] | |typeofObject[methodname]! = ' function ') {                            Throw NewError (' The method is not found ');                        }                    }                }            }; varC1 =NewComopsitimpl ();        Interface.ensureimplments (C1, Compositeinterface, formiteminterface); </script>

-Advantages and disadvantages of the interface:

-For some small and medium-sized programs, it is obviously unwise to use an interface, and the benefits of interfacing to the project are not obvious, but the complexity is increased.

-For the benefit of the interface, the first step is to improve the reuse of code, and for development, you can tell the programmer which classes are using which methods.

If you know the interface beforehand, then you reduce the time you encode the class and class conflicts, and implement decoupling. It is also easy for testing and debugging.

For JavaScript's weakly typed languages, type mismatches are common and it can be easier to use interfaces.

  

JS design mode

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.