下面是JAVASCRIPT设计模式书上讲的接口的定义。鸭式辩型法
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
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 expected method names to be '
+ 'passed in as a string.');
}
this.methods.push(methods[i]);
}
};
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 implements the " + interface.name + " interface.Method " +
method + " was not found.");
}
}
}
};
// 定义接口
var DynamicMap = new Interface('DynamicMap', ['centerOnPoint', 'zoom', 'draw']);
function displayRoute(mapInstance){
// 接口实现检查
Interface.ensureImplements(mapInstance, DynamicMap);
mapInstance.centerOnPoint(24, 13);
mapInstance.zoom(5);
mapInstance.draw();
}
// 对象
function Foo(){
}
Foo.prototype = {
centerOnPoint : function(x, y){
document.writeln('<br />centerOnPoint: ' + x + ', ' + y);
},
zoom : function(level){
document.writeln('<br />zoom: ' + level);
},
draw : function(){
document.writeln('<br />draw');
}
};
var foo = new Foo();
displayRoute(foo);
</script>
</head>
</html>