码迷,mamicode.com
首页 > 编程语言 > 详细

《Javascript设计模式》笔记二 接口

时间:2014-12-13 21:38:10      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   java   

在Javascript当中模仿接口的方法有三种:注释法,属性检查法和鸭式变形法。三者结合令人满意。

1.注释法

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

//用注释法模仿接口

var Com = function(id,method,action){}

Com.prototype.add = function(child){};

Com.prototype.remove = function(child){};

Com.prototype.getChild = function(index){};

Com.prototype.save = function(){}

注释法缺点:没有检查,也不会抛出错误,靠自觉。

注释法优点:易于实现,重用性。

2.属性检查法

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

//用属性检查法模仿接口
var Composite = function(id,meothod,action){
    this.implementsInterfaces = [‘Composite‘,‘FormItem‘];
};

function addForm(formInstance){
    if(!implements(formInstance,‘Composite‘,‘FormItem‘)){
        throw new Error(‘Object does not implement a required interface‘);
    }
}

function implements(object){
    for(var i = 1; i < arguments.length; i++){
        var interfaceName = arguments[i];
        var interfaceFound = false;
        for(var j = 0; j < object.implementsInterfaces.length; j++){
            if(object.implementsInterfaces[j] == interfaceName){
                interfaceFound = true;
                break;
            }
            
        }
        if(!interfaceFound){
            return false;
        }
    }
    return true;
}

3.填鸭变型法

var Composite = new Interface(‘Composite‘,[‘add‘,‘remove‘,‘getChild‘]);

var FormItem = new Interface(‘FormItem‘,[‘save‘]); 

var CompositeForm = function (id,method,action){ 

}; 

 function addForm () {
        ensureImplements(formInstance,Composite,FormItem);
};

《Javascript设计模式》笔记二 接口

标签:style   blog   io   ar   color   os   sp   for   java   

原文地址:http://www.cnblogs.com/hanweb/p/4161838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!