`
topcss
  • 浏览: 99579 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
文章分类
社区版块
存档分类
最新评论

JAVASCRIPT设计模式书上讲的接口的定义,鸭式辩型法

 
阅读更多

下面是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>	
	
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics