zoukankan      html  css  js  c++  java
  • 鸭式辨型法实现接口

    //声明接口类,用于实例化接口
    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();
  • 相关阅读:
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的Hbase操作
    熟悉的HDFS操作
    爬取晨星网对各公司主要职位的分析
  • 原文地址:https://www.cnblogs.com/wkzhao/p/10479408.html
Copyright © 2011-2022 走看看