Javascript design mode-Interface

Source: Internet
Author: User

I recently read the book "Pro JavaScript design pattrens" in the Javascript design mode. I think it is very good and can improve my understanding of JS oo, it may also help you better understand the JS library written by others and improve your JS level.

The first important content in this book is interfaces.

Everyone should be familiar with Interfaces. Simply put, interfaces are a contract or specification. Interfaces can be easily implemented in a strong facial object language. However, there is no native method for creating or implementing interfaces in Javascript, or determining whether a type has implemented an interface. We can only simulate interfaces with the flexibility of Js.

 

There are three methods to implement interfaces in javascript: annotation description, property verification, and duck model.

Note: I am reading English documents and have limited translation skills. I don't know how to translate some words. You can only understand the spirit.

 

1. Describing interfaces with comments)

Example:

/*interface Composite {       function add(child);       function remove(child);       function getChild(index); } interface FormItem {       function save(); } */ var CompositeForm = function(id, method, action) { // implements Composite, FormItem       ... }; //Implement the Composite interface. 
CompositeForm.prototype.add = function(child) { ... }; CompositeForm.prototype.remove = function(child) { ... }; CompositeForm.prototype.getChild = function(index) { ... }; // Implement the FormItem interface.
CompositeForm.prototype.save = function() { ...};

 

Simulate other object-oriented languages and use the interface and implements keywords, but you need to comment them out so that there will be no syntax errors.

This is only intended to tell other programmers what methods these classes need to implement. However, there is no authentication method. Whether these classes correctly implement the methods in these interfaces is a documented approach.

 

2. emulating interfaces with attribute checking)

Example:

/* interface Composite {     function add(child);     function remove(child);     function getChild(index); } interface FormItem {     function save(); } */ var CompositeForm = function(id, method, action) {     
this.implementsInterfaces = ['Composite', 'FormItem']; ... };
...
function addForm(formInstance) { if(!implements(formInstance, 'Composite', 'FormItem')) {     throw new Error("Object does not implement a required interface.");   }   ... }// The implements function, which checks to see if an object declares that it // implements the required interfaces. function implements(object) {   for(var i = 1; i < arguments.length; i++) {     // Looping through all arguments     // after the first one.     var interfaceName = arguments[i];     var interfaceFound = false;    for(var j = 0; j < object.implementsInterfaces.length; j++) {       if(object.implementsInterfaces[j] == interfaceName) {         interfaceFound = true;         break;       }     }    if(!interfaceFound) {       return false;       // An interface was not found.    }   }  return true; // All interfaces were found.
}

 

This method is better than the first method. The interface definition is still implemented in the form of annotations, but a verification method is added to determine whether a type has implemented an interface.

 

3. Duck type (emulating interfaces with duck typing)

// Interfaces. 
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);

// CompositeForm class
var CompositeForm = function(id, method, action) {
  ...
};
...
function addForm(formInstance) {
  ensureImplements(formInstance, Composite, FormItem);
  // This function will throw an error if a required method is not implemented.
  ...
}// Constructor.
var Interface = function(name, methods) {
  if(arguments.length != 2) {
    throw new Error("Interface constructor called with "
             + arguments.length + "arguments, but expected exactly 2.");
  }  this.name = name;
  this.methods = [];
  for(var i = 0, len = methods.length; i < len; i++) {
    if(typeof methods[i] !== 'string') {
      throw new Error("Interface constructor expects method names to be "
              + "passed in as a string.");
    }
    this.methods.push(methods[i]);
  }
}; // Static class method.
Interface.ensureImplements = function(object) {
  if(arguments.length < 2) {
    throw new Error("Function Interface.ensureImplements called with "
              +arguments.length + "arguments, but expected at least 2.");
  } for(var i = 1, len = arguments.length; i < len; i++) {
    var interface = arguments[i];    if(interface.constructor !== Interface) {
      throw new Error("Function Interface.ensureImplements expects arguments"
              + "two and above to be instances of Interface.");
    }    for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
      var method = interface.methods[j];
      if(!object[method] || typeof object[method] !== 'function') {
        throw new Error("Function Interface.ensureImplements: object "
                + "does not implement the " + interface.name + " interface. Method " + method + " was not found.");
      }
    }
  }
};

 

 

When to use interfaces?

 

Strict type verification is not suitable because most JavaScript programmers have been programming for years without interface and Interface Verification. When you start designing a complex system in the design mode, using interfaces is more helpful. It seems that using interfaces limits the flexibility of JavaScript, but in fact it makes your code more loosely coupled. It makes your code more flexible. You can transmit any type of variables and ensure that you have the method you want. There are many scenario interfaces that are very suitable for use.

In a large system, interfaces become necessary when many programmers participate in development projects. Programmers often access an API that has not yet been implemented, or provide other programmers with a method stub that others depend on. In this case, the interface becomes quite valuable. They can document APIs and act as programming contracts. You can immediately know when a stub is replaced by an implemented API. If the API changes during development, it can be seamlessly replaced by another method that implements this interface.

 

How to use interfaces?

 

The first problem to be solved is whether the interface is suitable in your code. If it is a small project, using interfaces will increase the complexity of the Code. Therefore, you must determine whether the benefits outweigh the disadvantages when using interfaces. If you want to use an interface, the following suggestions are provided:

1. reference the interface class to your page file. Interface source file you can find the following site: http://jsdesignpatterns.com /.

2. Check your code and determine which methods need to be abstracted into the interface.

3. Create an interface object. No interface object contains a set of related methods.

4. Remove all constructors for verification. We will use the third interface implementation method, namely the duck type.

5. Use interface. ensureimplements to replace the constructor verification.

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.