首页 > 语言 > JavaScript > 正文

javascript设计模式 接口介绍

2024-05-06 14:21:34
字体:
来源:转载
供稿:网友
这本书中第一个重要的内容就是接口。

大家对接口应该都不陌生,简单的说接口就是一个契约或者规范。在强类型的面相对象语言中,接口可以很容易的实现。但是在javascript中并没有原生的创建或者实现接口的方式,或者判定一个类型是否实现了某个接口,我们只能利用js的灵活性的特点,模拟接口。
在javascript中实现接口有三种方式:注释描述、属性验证、鸭子模型。
note:因为我看的是英文书,翻译水平有限,不知道有些词汇如何翻译,大家只能领会精神了。
1. 注释描述 (Describing Interfaces with Comments)
例子:
代码如下:
/*
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() {
...
};

模拟其他面向对象语言,使用interface 和 implements关键字,但是需要将他们注释起来,这样就不会有语法错误。
这样做的目的,只是为了告诉其他编程人员,这些类需要实现什么方法,需要在编程的时候加以注意。但是没有提供一种验证方式,这些类是否正确实现了这些接口中的方法,这种方式就是一种文档化的作法。
2. 属性验证(Emulating Interfaces with Attribute Checking)
例子:
代码如下:
/* 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;
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选