• 鸭式辨型法实现接口


    //声明接口类,用于实例化接口
    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();
  • 相关阅读:
    Redis教程_2
    Redis教程_1
    机器学习概念_2
    机器学习概念_1
    [极客大挑战 2019]LoveSQL
    [极客大挑战 2019]EasySQL
    [SUCTF 2019]EasySQL
    [强网杯 2019]随便注
    [HCTF 2018] WarmUp
    php代码函数笔记
  • 原文地址:https://www.cnblogs.com/wkzhao/p/10479408.html
Copyright © 2020-2023  润新知