• 鸭式辨型法实现接口


    //声明接口类,用于实例化接口
    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();
  • 相关阅读:
    Linux环境变量$PATH
    grep
    echo命令
    ip命令
    浅析Linux下的/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc文件
    shell脚本4种执行方式
    /proc路径
    tr命令
    Linux命令cut
    前端论坛网站知识
  • 原文地址:https://www.cnblogs.com/wkzhao/p/10479408.html
Copyright © 2020-2023  润新知