Implementation of interface of javascript-design pattern __javascript

Source: Internet
Author: User

In JS, and there is no real sense of the interface, we can only simulate the way the interface effect, use the interface can promote the reuse of code, reduce the coupling between the code, reduce code errors and find the cause of error, the disadvantage is to increase the amount of code, and can not force programmers to implement interface. JS analog interface in the way there are three kinds. first: How to Annotate

This approach, which is displayed using annotations, tells the programmer what interfaces need to be implemented, in a way that relies entirely on the programmer's awareness, and whether the interface is actually implemented and cannot be checked for any assistance in debugging the Code, which, in contrast, does not have an impact on code performance.

/**
  * Annotation based implementation-the interface code in the annotation, for the program does not have any effect, just to the programmer to see.
  *
  This is a Game interface with a Playgames method
  *public Interface Game {* Public      void Playgames ();
  *} * *
  This is a Food interface with a eat method * Public
  interface Food {* Public      void Eat ();
  * *
  *
 /var person = function (name) {
     this.name = name;
 According to the content of the annotation, consciously implement the method in the interface
 Person.prototype.playGames = function () {
     alert (THIS.name + "playing game!")
 };
 Person.prototype.eat = function () {
     alert (this.name + "at dinner!")
 };
 Create Object P
 var p = new Person ("xiaoming");
 Call Method
 P.playgames ();
second: Using attributes to check whether an interface is implemented

This approach is an extension of the first way, declaring the interface name that needs to be implemented in the object's properties, and then designing the way to detect whether the object implements the specified interface, which is a disadvantage, and there is no way to detect whether the method in the interface is actually implemented.

 /** * Annotation based implementation-the interface code in the annotation, for the program does not have any effect, just to the programmer to see.
  * This is a Game interface with a Playgames method *public interface Game {* public void playgames ();
  *} * * This is a Food interface with a eat method * Public interface Food {* public void eat ();
     */var person = function (name) {//By the way of the property, declare a property, the value is the interface name to be implemented This.implinterfaces = ["Game", "Food"];
 THIS.name = name;
 };
 According to the content of the annotation, consciously implement the method Person.prototype.playGames = function () {alert (THIS.name + "playing game!")
 };
 Person.prototype.eat = function () {alert (this.name + "at dinner!")
 };
 Create Object p var p = new Person ("xiaoming");

 Call Method P.playgames (); Defines whether a class that detects a person object implements the specified interface function Checkperson (person) {//calls a public method for judgment, if returned false, indicates that the interface is not implemented, throws an error if (!checki
 Mplements (person, "fightable", "walkable")) throw new Error ("must implement fightable and walkable interface");
 }; Defines a public method used to detect whether a class of an object implements the specified interface function checkimplements (obj) {//If the object does not have an interface property, the interface is not implemented and an error is thrown if (!obj.implinterfa
     CES) throw new Error ("must declare the implemented interface");There is an object arguments in each method to store the actual arguments passed in//arguments the containing object itself and the parameter string, so traversal begins with subscript 1, skipping the object itself for (var i = 1; i < arguments . length;
         i++) {if (typeof Arguments[i]!= "string") throw new Error (Arguments[i] + "incorrect type");
         var found =false;
             for (var j = 0; J < Obj.implInterfaces.length; J + +) {var inter = obj.implinterfaces[j];
                 Detects if the implemented interface is correct if (inter = = Arguments[i]) {found = true;
             Break
     } if (!found) return false;
 return true;
 }; Check whether the class containing the object P implements the interface Checkperson (p);
The third type: Duck type identification mode

Duck type (this name comes from James Whitomb Riley's famous quote: "Walk like a duck and rattle a Duck"), meaning to judge whether a method implements an interface, just see if it contains all the methods in the interface, and if it does, We can assume that this approach implements this interface.

1, first define a function to create the interface

Defines an interface method with an array of length 2, the first element of the array is an object interface object, the second element is an array of interface methods,
var Interface = function (name) {
    //arguments is an actual incoming parameter
    if (arguments.length!= 2) throw new Error ("The interface created does not conform to the standard, there must be two parameters, the second parameter is the method of the interface");
    this.name = name;
    This.methods = [];
    Gets the method array
    var methods = arguments[1];
    for (var i = 1; i < methods.length i++) {
        this.methods.push (methods[i]);
    }
;

2, the use of the above function to declare 2 interfaces and create an object implementation interface method

Method of declaring two interfaces and interfaces
 var Game = new Interface ("Game", ["playgames"]);
 var Food = new Interface ("Food", ["Eat", "Throwfood"]);
 var person = function (name) {
     this.name = name;
 };
 Three methods to implement the interface
 Person.prototype.playGames = function () {
     alert (THIS.name + "playing game!");
 Person.prototype.eat = function () {
     alert (this.name + "at dinner!");
 Person.prototype.throwFood = function () {
     alert (this.name + "Discard food");
 Create Object P
 var p = new Person ("xiaoming");

3, write methods to detect whether the object implements the interface method

The method used to detect whether an object implements an interface, an array of parameters, the first element as an object, and the remaining element as an implemented interface object
interface.checkimplements = function (obj) {
   if ( Arguments.length < 2 throw new Error ("The interface to be checked must pass in the parameters of the interface object, the number of parameters must be greater than or equal to 2");
   for (var i = 1; i < arguments.length i++) {
       var intobj = arguments[i];
       if (intobj.constructor!= Interface) throw new Error (Intobj + "interface object is incorrect");
       Check whether the method meets the requirements of
       var cmethods = intobj.methods;
       for (Var j =0 J < Cmethods.length J + +) {
           if (!obj[cmethods[j]] | | typeof obj[cmethods[j]]!= "function") throw new Error ("must be implemented:" + cmethods[j] + "This method");}

4, detect whether the object is implemented in the specified Interface object method

function Checkperson (person) {
    //Call detection method, passing in the object to be detected and the interface object it needs to implement
    interface.checkimplements (Person,game,food );
};
Detecting whether the object P implements the interface
Checkperson (p);

Can be used in conjunction with the first method

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.