JavaScript中的界面模式的运行示例或工作演示 [英] A running example or working demo of Interface pattern in JavaScript

查看:94
本文介绍了JavaScript中的界面模式的运行示例或工作演示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读专业JavaScript设计模式书,并且在了解第2章中给出的界面模式时几乎没有困难,因为没有一个完整的代码示例来说明这种模式的使用。 >

我正在寻找一些帮助,了解这种模式,一些运行的代码示例可能在jsfiddle等。



此模式是在第14-22页的书中解释,我不明白的主要内容是在哪里和如何调用addForm方法。 OR
如果有人可以使用一些测试数据和对象来完成ResultFormatter示例,这将非常有助于理解模式。



这本书的代码Pro Javascript设计模式可从 http://jsdesignpatterns.com/ 下载,这是第2章。



感谢您的帮助!!

解决方案

方法,但这个想法很简单:


  1. 你有一些类 - 你的界面 - 只是指定一些功能的名称。 (您可能希望有一个名为Interface的类,您的实际接口实例化,因此您的接口类型为Interface)

  2. 然后,您还可以使用其他实现此接口的类。这意味着这个第二个类必须至少具有接口指定的所有函数。

  3. 最后,你还有一些其他功能,希望接收一个实现接口的对象。在你提到的示例代码中,这个函数是addForm,它需要一个实现'Composite'和'FormItem'接口的对象。

  4. 然后这个函数循环遍历接口的所有方法(s)它期望,并检查您传入的对象也有这些方法。如果在传入函数的对象中没有找到一个接口的方法,它会确定对象不实现接口,并引发异常。

有些人可能会发现这种模式是不切实际的,因为涉及的开销,但是由于Javascript缺乏对接口的本机支持,这并不是一个太糟糕的解决方案。有些人可能会发现使用Javascript中的小项目的接口是过度的。



示例

  var Interface = function(name,methods){
this.name = name;
this.methods = [];

if(methods.constructor == Array)
this.methods = methods;
else if(methods.constructor == String)
this.methods [0] =方法;
else
throw new Error(Interface must defined methods as a String or a Array of Strings);
};

var InterfaceHelper = {
ensureImplements:function(obj,interfaces){
//如果接口不是数组,假定它是一个函数指针
var toImplement = interfaces.constructor == Array?接口:[interfaces];
var interface;

//对于obj必须实现的每个接口:
for(var i = 0,len = toImplement.length; i< len; i ++){
interface = toImplement [一世];

//确保它确实是一个接口
if(interface.constructor!= Interface)
throw new Error(对象尝试实现非接口
+ interface.name +不是接口);

//确保obj具有接口
中描述的所有方法(var j = 0,interfaceLen = interface.methods.length; j< interfaceLen; j ++)
if(!obj [interface.methods [j]])
throw new Error(接口方法未实现
+ interface.name +定义方法+ interface.methods [j] );
}

返回true;
}
};

var Drawable = new Interface(Drawable,[onDraw]);

var Surface = function(){
this.implements = [Drawable];

this.onDraw = function(){
console.log(Surface Drawing);
};
};

用法

  var myDrawableSurface = new Surface(); 

//返回true
InterfaceHelper.ensureImplements(myDrawableSurface,Drawable);

//返回false(抛出错误)
InterfaceHelper.ensureImplements(myDrawableSurface,Array);


I am reading the "pro javascript design patterns" book and finding little difficulty in understanding the "Interface" pattern given in the book chapter 2 as there isn't a complete code example demonstrating the use of this pattern.

I am looking for some help understanding this pattern with some running code example may be on jsfiddle etc.

This pattern is explained in the book pages 14 - 22, main point I am not understanding is where and how "addForm" method is called. OR if somebody can complete the ResultFormatter example with some test data and object this will really be very helpful in understanding the pattern.

Code for the book "Pro Javascript Design Patterns" can be downloaded from http://jsdesignpatterns.com/ and this is Chapter 2.

Thanks for the help !!

解决方案

I have seen the pattern implemented in different ways, but the idea is simple:

  1. You have some class - your interface - that simply specifies the names of some functions. (You may want to have a class called Interface that your actual interfaces instantiate, just so your interfaces are of type Interface)
  2. You then have some other class that implements such interface. This means that this second class must have at least all of the functions specified by the interface.
  3. Finally, you have some other function somewhere else, that expects to receive an object that implements the interface. In the sample code you mention, this function is addForm, which expects an object that implements the 'Composite' and 'FormItem' interfaces.
  4. This function then loops through all the methods of the interface(s) it expects, and checks that the object you passed in to it also have those methods. If a method from one of the interfaces is not found in the object passed into the function, it determines that object doesn't implement the interface, and throws an exception.

Some people may find this pattern unpractical because of the overhead involved, but given Javascript's lack of native support for interfaces, this is not too bad a solution. Some people may also find that using interfaces for small projects in Javascript is overkill.

Example

var Interface = function(name, methods) {
    this.name = name;
    this.methods = [];

    if (methods.constructor == Array)
        this.methods = methods;
    else if (methods.constructor == String)
        this.methods[0] = methods;
    else
        throw new Error("Interface must define methods as a String or an Array of Strings");
};

var InterfaceHelper  = {
    ensureImplements : function(obj, interfaces) {
       // If interfaces is not an array, assume it's a function pointer
       var toImplement = interfaces.constructor == Array ? interfaces : [interfaces];
       var interface;

       // For every interface that obj must implement:
       for (var i = 0, len = toImplement.length; i < len; i++) {
          interface = toImplement[i];

          // Make sure it indeed is an interface
          if (interface.constructor != Interface)
             throw new Error("Object trying to implement a non-interface. "
             + interface.name + " is not an Interface.");

          // Make sure obj has all of the methods described in the interface
          for (var j = 0, interfaceLen = interface.methods.length; j < interfaceLen; j++)
             if (!obj[interface.methods[j]])
                throw new Error("Interface method not implemented. " 
                + interface.name + " defines method " + interface.methods[j]);
       }

       return true;
    }
};

var Drawable = new Interface("Drawable", ["onDraw"]);

var Surface = function() {
   this.implements = ["Drawable"];

   this.onDraw = function() {
      console.log("Surface Drawing");
   };
};

Usage

var myDrawableSurface = new Surface();

// Returns true
InterfaceHelper.ensureImplements(myDrawableSurface, Drawable);

// Returns false (Error thrown)
InterfaceHelper.ensureImplements(myDrawableSurface, Array);

这篇关于JavaScript中的界面模式的运行示例或工作演示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆