"JavaScript design mode" Reading note one (interface)

Source: Internet
Author: User

1. What is an interface


The parents who have studied design patterns may have heard of a principle of programming: "Programming for interfaces rather than implementing programming". So what exactly is an interface?

An interface defines the means by which an object should have those methods, but does not specify the specific implementation of these methods. Learning C #, or vb.net, may be clear. The so-called interface is a special class that has only the method name but not the implementation.


Vb. The interfaces in net

Public Interface A person    sub Say ()    sub Eat () End interfacepublic Class Mans Implements Person public    Sub Eat () Implements person.eat    End Sub Public    sub Say () Implements Person.say    End subend Class

Note: In vb.net, the compiler will make an error if the implementation class does not implement all the methods in the interface.

The problem is that JavaScript does not have a built-in method for creating or implementing interfaces, nor does it have built-in methods that can be used to determine whether an object implements an interface. But through a certain imitation, it is the realization of the so-called interface.


Emulation interface in 2.JavaScript


1) Describe the interface with annotations

/* A human Interface interface person {    function say (); function eat ();} *///in the above comments simply defines the name and method of the interface, and then by looking at annotations directly implement the interface can be var man = function (id, method, action) {//Implement the person this interface    ...};// Implement the method in the interface Man.prototype.say = function () {    ...}; Man.prototype.eat = function () {    ...};

The simplest kind of writing, because the interface is not specifically implemented, as long as the knowledge to implement the function can be, so to implement the interface written into the comments, let the implementation of the class know how to implement.


2) use attribute check to imitate interface

This approach is slightly tighter than describing the interface with annotations, declaring that you have implemented those interfaces and that objects that you want to deal with can be checked against the claims. At this point, the interface is still a comment, but there is a way to check the properties, which means that a class implements that interface.


3) Duck Type Imitation interface

interfaces.//defines an interface var Composite = new Interface (' Composite ', [' Add ', ' Remove ', ' getchild ']); var FormItem = new Interfa CE (' FormItem ', [' Save ']);//define a class var compositeform = function (id, method, action) {   ...}; ... function addform (forminstance) {    ensureimplements (forminstance, Composite, FormItem);    If you do not implement all the methods in the interface, an error will be thrown ...    }

It is very simple to determine the implementation of an interface, as long as the method name in a class is consistent with the interface, it is considered to be the implementation of this interface. It's like hearing a quack called a duck.

3. The process of imitating an interface


1) Those who have studied other languages, we know that the so-called interface is a collection of methods that are not implemented. So if you want to mimic an interface, in JavaScript, we have to add a member of the array to the Interface class:methods, which is used to save our method names. Another parameter is required:name. To make it easy for us to detect which interface the implementation class implements.

2) as shown in the interface written in C # above, if a class inherits an interface in C #, but does not implement its methods in its entirety, the compiler will alert us by giving an error. But JavaScript doesn't have this feature. So we need to define a common approach: ensureimplements. To remind us whether the implementation class implements all the methods of the interface.


4. Implementation code of the interface


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >/* * Interface class constructor, accept more than 2 parameters, where the first parameter is the interface name, the following argument can be a string array, or a string * @param {Object} name * Interface Name * @param {Object} methods * Interface contains A collection of methods, parameters can be an array, or you can pass in any number of string forms of the method name */var Interface = function (name, methods) {if (Arguments.length < 2) {//If the number of arguments is not 2, Throws the error throw new error ("Interface constructor called with" + Arguments.length + "arguments, but expected at least 2");} THIS.name = Name;this.methods = [];for (var i = 1, len = arguments.length; i < Len; ++i) {if (Arguments[i] instanceof Arra Y) {//If the parameter is an array, the parameter is traversed for (var j = arguments[i].length-1; j >-1;--j) {if (typeof Arguments[i][j]!== ' string ') {//Guaranteed incoming method The name is string, otherwise throws an error throw new error (' Interface constructor expects method names to being passed in as a string ');} This.methods.push (Arguments[i][j]); Save method Name}} else if (typeof arguments[i] = = = ' String ') {//parameter is string, save directly This.methods.push (Arguments[i]);} else {// Otherwise throws the error throw new error (' Interface constructor expects method names to being passed in as a string ');}}};/ ** The interface implements the check function, the first parameter is the object to be checked, any subsequent arguments are implemented interface objects, or an array of interface objects * @param {Object} object */interface.ensureimplents = function ( Object) {if (Arguments.length < 2) {throw new Error ("Interface constructor called with" + Arguments.length + "arguments, b UT expected at least 2 ");}  var _checkmethods = function (inface) {//intrinsic function, used to verify that the object implements the method in the IFS object var methods = inface.methods, I = methods.length -1;for (; i >-1; i) {var method = methods[i];//If the object does not exist, or if the property is not a method, then throws an error if (typeof object[method] = = = ' undefined ' | | typeof Object[method]!== ' function ') {throw new Error ("function Interface.ensureImplents:object does not implent the" + Inface.name + "interface. Method "+ Method +" is not found. ");}}; for (var i = arguments.length-1; i > 0; i.) {if (Arguments[i] instanceof Array) {for (var j = arguments[i].length-1; J >-1; --J) {if (!arguments[i][j] instanceof Interface) {throw new Error (' Function interface.ensureimplents expects arguments Both and above to being ' + ' instances of Interface ');} _chEckmethods (Arguments[i][j]); Verify the interface implementation}} else if (Arguments[i] instanceof Interface) {_checkmethods (arguments[i]);//Verify the interface implementation} else {throw new Error (' Function Interface.ensureimplents expects arguments and above to be ' + ' instances of Interface ');}}; </span>


5. Kind


<script src= "Javascript/jquery-1.3.1.js" ></script>    <script src= "Javascript/interface.js" > </script>    <script>        //define a human interface with two methods say and eat        var IPerson = new Interface (' IPerson ', ' say ', ' Eat ');        Defines the class that implements the interface        var man = {            say:function () {                alert ("I Speak")            ,            eat:function () {                alert ("I Can Eat") c11/>}        }        //Define a method that verifies whether the implementation is implemented by        function test (itestinstance) {            //invokes the authentication method in the interface to verify that the Intern class implements all the methods            Interface.ensureimplents (Itestinstance, IPerson);            Itestinstance.say ();            Itestinstance.eat ();        }        Test (man); Popup Two dialog    </script><span style= "Font-size:18px;color: #c0c0c0;" ></span>



6. Summary


Interface brings us convenience, but also brings a lot of difficulties, especially in JavaScript, also need to use auxiliary classes and methods to enforce a class implementation of an interface, so with no interface, but also need to combine the specific circumstances to judge.


6. Summary


Interface brings us convenience, but also brings a lot of difficulties, especially in JavaScript, also need to use auxiliary classes and methods to enforce a class implementation of an interface, so with no interface, but also need to combine the specific circumstances to judge.



"JavaScript design mode" Reading note one (interface)

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.