JavaScript design Pattern Interface Introduction _javascript skills

Source: Internet
Author: User
Tags static class stub
The first important element in this book is the interface.

We should be familiar with the interface, simply say that the interface is a contract or specification. In strongly typed object-oriented languages, interfaces can be easily implemented. But in JavaScript there is no original way to create or implement interfaces, or to determine whether a type implements an interface, we can only use the characteristics of JS flexibility, analog interface.
There are three ways to implement interfaces in JavaScript: annotation descriptions, attribute validation, and duck models.
Note: Because I read English books, the level of translation is limited, do not know how to translate some words, we can only understand the spirit.
1. Note Description (describing interfaces with Comments)
Example:
Copy Code code 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, using interface and implements keywords, but you need to annotate them so that there is no syntax error.
The goal is simply to tell other programmers what methods these classes need to implement and need to be aware of when programming. But there is no way to verify that these classes implement the methods in these interfaces correctly, which is a documented approach.
2. Attribute verification (emulating interfaces with attribute Checking)
Example:
Copy Code code 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 = 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 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 is not found.
}
}
return true;
All interfaces were found.
}

This approach is better than the first, and the definition of the interface is still implemented as annotations, but a validation method is added to determine whether a type implements an interface.
3. Duck type (emulating interfaces with Duck Typing)
Copy Code code as follows:

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 would 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"
+ "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" "+ Interface.name +" interface. Method "+ Method +" is not found. ");
}
}
}
};

When do I use an interface?
It is not appropriate to use strict type validation all the time because most JavaScript programmers have been programming for years without interface and interface validation. When you start designing a complex system with design patterns, it is more useful to use interfaces. It seems that using an interface may limit JavaScript flexibility, but in fact he makes your code more loosely coupled. He makes your code more flexible, you can transfer any type of variable and make sure that he has the method you want. There are many scene interfaces that are ideal for use.
In a large system, many programmers are involved in development projects, and interfaces become necessary. The interface becomes quite valuable in cases where programmers often have access to an API that has not yet been implemented, or to provide other programmers with a method stub that others rely on. They can document the API and act as a contract for programming. When the stub is implemented by the API, you can immediately know that if the API changes during the development process, he can be replaced seamlessly by another method that implements the interface.
How do I use an interface?
The first thing to solve is whether the interface is appropriate in your code. If it is a small project, using an interface increases the complexity of the code. So you want to determine whether the use of the interface in the case of the benefits outweigh the drawbacks. If you want to use an interface, here are a few suggestions:
1. Refer to the interface class to your paging file. Interface source files you can find the following site: http://jsdesignpatterns.com/.
2. Check your code to determine which methods need to be abstracted into the interface.
3. Create interface object, no interface object contains a set of related methods.
4. Remove all constructor validations, we will use the third interface implementation, that is, the duck type.
5. Replace constructor validation with interface.ensureimplements.
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.