首页 > Web开发 > 详细

js实现接口

时间:2015-11-17 23:15:24      阅读:281      评论:0      收藏:0      [点我收藏+]

接口的实现方式

/**
             * 接口类
             * @param {String} name 接口名称
             * @param {Array} methods 接口方法数组
             */
            function Interface(name, methods) {
                //校验变量,输入参数必须为2
                if (arguments.length !== 2) {
                    throw new Error("state one interface require 2 parameters");
                }
                this.name = name;
                this.methods = [];
                if (methods.length <= 0) {
                    throw new Error(this.name + ": interface method must state");
                }
                for (var i = 0; i < methods.length; i++) {
                    if (typeof methods[i] !== "string") {
                        throw new Error(this.name + ": " + method[i] + ": interface method must be string ");
                    }
                    this.methods.push(methods[i]);                    
                }
            }
            
            //创建一个接口
            var Composite = new Interface("composite", ["add", "delete"]);
            
            //实现接口的类
            function CompositeImpl() {
                                
            }
            
            CompositeImpl.prototype.add = function() {
                console.log("add...");
            };
            
            CompositeImpl.prototype.delete = function() {
                console.log("delete...");
            };
            
            //申明一个实例
            var c1 = new CompositeImpl();
                    
            /**
             * 校验方法
             * @param {Object} object
             */
            function checkClassImplementInterface(object) {
                if (arguments.length < 2) {
                    throw new Error("check interface is required 2 parameters");
                }
                
                var implementInterfaces = {};
                
                for (var i = 1; i < arguments.length; i++) {
                    implementInterface = arguments[i];
                    var implementInterfaceMethods = implementInterface.methods;
                    
                    for (var j = 0; j < implementInterfaceMethods.length; j++) {
                        if (!object[implementInterfaceMethods[j]] || typeof object[implementInterfaceMethods[j]] !== "function") {
                            throw new Error(implementInterface.name + "." + implementInterfaceMethods[j] + " id not method ");
                        }
                    }
                }
            }
            
            //检查类是否实现了全部接口
            checkClassImplementInterface(c1, Composite);
            

 

js实现接口

原文:http://www.cnblogs.com/zhaojunyang/p/4973158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!