在Javascript中模仿接口(一)

本文探讨了在JavaScript中如何通过注释、属性检查和鸭式辨型三种方式模仿和实现接口,提供了实例代码和解释,帮助理解接口在面向对象编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在JavaScript中模仿接口——本文摘自《JavaScript设计模式》

 

一、用注释描述接口

 

	/*
		interface Composite {
			function add(child);
			function remove(child);
			function getChild(index);
		}

		interface FormItem {
			function save();
		}
	*/

	var CompositeForm = function(id, method, action){
		//......
	};

	//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(){
		//......
	}
 

这种模仿并不是很好,他们有为确保CompositeForm真正实现正确的方法集而进行检查,

也不会跑出错误以高质程序员程序中的问题。

 

二、用属性检查模仿接口

 

	
	/*
		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 delcares that it
	//implements the required interfaces.

	function implements(object){
		for(var i = 0; i < arguments.length; i++){
			var interfaceName = arguments[i];
			var interfaceFound = false;
			for(var j = 0; j < object.implementsInterface.length; j++){
				if(object.implementsInterface[j] == interfaceName){
					interfaceFound = true;
					break;
				}
			}
			if(!interfaceFound){
				return false; //An interface was not found.
			}
		}
		return true; //All interface were found.
	}
 

在这个例子中,CompositeForm宣传自己实现了Composite和FormItem这两个接口,其做法是吧这链各个接口的

名称加入一个名为implement上Interfaces的数组。

 

三、用鸭式辨型模仿接口

//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(formInstancd){
		ensureImplements(formInstance, Composite, FormItem);
		//........
	}
 

待续……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值