码迷,mamicode.com
首页 > Web开发 > 详细

js实现接口

时间:2015-11-17 23:18:16      阅读:150      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!