JavaScript design pattern: interface emulation

Source: Internet
Author: User

There are three ways to mimic an interface in JavaScript

1. Annotation method

/* Interface Composite () {    function Add (child);    function remove (child);    function Getchild (index);} Interface FormItem () {    function Save ();} */

Cons: There is no way to ensure that the set of methods in the interface is actually implemented, nor does it throw an error to inform the user that there is a problem in the program and that it is not helpful for testing and debugging. It mainly belongs to the scope of the program document, in this practice, the adherence to the interface agreement relies entirely on self-consciousness.

Pros: No additional classes or functions are required and do not affect file size or execution speed because the annotations used can be rejected when the code is deployed

2. Property Check

The class explicitly supports any interface by adding an array property of implementsinterfaces, and any function that requires its arguments to be of a particular type can examine this property and throw an error when the desired interface is not declaring the column.

varcompositeform=function(ID, method, action) { This. implementsinterfaces=[' Composite ', ' FormItem '];}functionAddForm (forminstance) {if(!implements (forminstance, ' Composite ', ' FormItem ')){        Throw NewError (' Object does not implements a required interface '); }}functionimplements (object) { for(vari=1;i<arguments.length;i++){        varInterfacename=Arguments[i]; varInterfacefound=false;  for(varj=0;j<object.implementsinterfaces.length;j++){            if(object.implementsinterfaces[j]==InterfaceName) {Interfacefound=true;  Break; }        }        if(!interfacefound) {            return false; }    }    return true;}

Pros: Provides documentation for the interfaces implemented by the class. If the required interface is not in the list of interfaces declared by a class, you will see an error message.

Cons: There is no guarantee that the interface that actually implements the self-proclaimed implementation. You only know if it says you have implemented the interface. It is common to declare a class when it implements an interface, but then omit one of them when implementing the method specified by the interface. All checks pass at this point, but the required method does not exist, which will bury the hidden trouble in the code.

3. Duck method of distinguishing type

"Walking like a duck and quack is a duck." The class declares which interfaces it supports and is important, as long as it has the methods in those interfaces. If an object has all methods with the same name as an interface-defined method, it can be assumed that it implements this interface.

varComposite=NewInterface (' Composite ', [' Add ', ' Remove ', ' getchild ']);varformitem=NewInterface (' FormItem ', [' Save ']);varcompositeform=function(ID, method, action) {}functionAddForm (forminstance) {interface.ensureimplements (forminstance, Composite, FormItem);}varInterface=function(name, methods) {if(arguments.length!=2){        Throw NewError ("Interface constructor called with" +arguments.length+ "arguments, but expected exactly 2.")    }     This. name=name;  This. methods=[];  for(varI=0, len=methods.length;i<len;i++){        if(typeofmethods[i]!== ' String '){            Throw NewError (' Interface constructor expects method names to being passed in as a string '); }         This. Methods.push (Methods[i]); }}interface.ensureimplements=function(object) {if(arguments.length<2){        Throw NewError (' Function interface.ensureimplements called with ' +arguments.length+ ' arguments, but expected at least 2. '); }     for(varI=1, len=arguments.length;i<len;i++){        varInterface=Arguments[i]; if(arguments.constructor!=Interface) {            Throw NewError (' Function interface.ensureimplements expected arguments ' and above to ' instances of Interface '); }         for(varJ=0, methodslen=interface.methods.length;j<methodslen;j++){            varMethod=Interface.methods[j]; if(!object[method] | |typeofobject[method]!== ' function '){                Throw NewError (' Function Interface.ensureImplements:object does not implement the ' +interface.name+ ' Interface. Method ' +method+ ' is not found. '); }        }    }}

Disadvantage: The class does not declare which interfaces it implements, which reduces the reusability of the code and also lacks the self-descriptive nature of the other two methods. It needs to use an auxiliary class (Interface) and an auxiliary function (ensureimplements), which only cares about the name of the method and does not check the name, number, or type of the parameter.

JavaScript design pattern: interface emulation

Related Article

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.