Interface introduction of javascript Design Mode

Source: Internet
Author: User

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:
Copy codeThe Code is as follows:
/*
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:
Copy codeThe Code is as follows:
/* 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)
Copy codeThe Code is as follows:
// Interfaces.
Var Composite = new Interface ('composite ', ['add', 'delete', '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"
+ 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"
+ 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.

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.