鸭式辨型法实现接口

//声明接口类,用于实例化接口
function Interface(name,methods) {
    this.name = name;
    let functions = [];
    //方法名为字符串类型
    methods.forEach(method=>{
        if(typeof method !== "string"){
            throw new Error(`illegal arguments: '${method}'` );
        }
        functions.push(method);
    });
    this.methods = functions;
}

//实例化接口
const CompositeInterface = new Interface("Composite",["addComposite"]);
const FormInterface = new Interface("Form",["addForm"]);

//声明规则检测制定类是否实现了指定接口
function ensureInterFace(obj,interfaces) {
    //参数少于两个校验失败
    if(arguments.length <2){
        throw new Error("illegal arguments number");
    }

    //第2至N个参数为接口
    for(let i = 1;i<arguments.length;i++){
        let inf = arguments[i];
        if(inf.constructor !== Interface){
            throw new Error(`illegal arguments type.'${inf}' must be a interface`);
        }

        //遍历接口的每个method是否被实现
        let methods = inf.methods;
        methods.forEach(method =>{
            if(!obj[method] || typeof obj[method] !== "function"){
                throw new Error(`method '${method}' must be implemented`);
            }
        })
    }
}


function CompositeForm() {

}

CompositeForm.prototype.addComposite = function () {
    console.log("addComposite");
};

CompositeForm.prototype.addForm = function () {
    console.log("addForm");
};


let compositeForm = new CompositeForm();

ensureInterFace(compositeForm,CompositeInterface,FormInterface);

//test
compositeForm.addComposite();

 

posted @ 2019-03-05 20:25  gluawwa  阅读(232)  评论(0编辑  收藏  举报