Javascript模式(三) 策略模式

var data = {
        "username" : "zhangsan",
        "password" : "12345690",
        "code" : "abcd"
    };

    var validate = {
        rules : {},
        config : {},
        msg : [],
        check : function(data){
            var k, rule, config, checker;
            rule = this.rules;
            config = this.config;
            this.msg.length = 0;
            for(k in data){
                if(data.hasOwnProperty(k)){
                    if(!rule[k]){
                        throw new Error("validate.check error, error type: " + k + " not exist");
                    }
                    checker = this.rules[k];
                    if(!checker.validate(data[k])){
                        this.msg.push(checker.msg);
                    }
                }
            }
        }
    };

    validate.rules.username = {
        validate : function(username){
            return username.length > 7;
        },
        msg : "用户名有误"
    };

    validate.rules.password = {
        validate : function(password){
            return password.length > 7
        },
        msg : "密码挂了"
    };

    validate.rules.code = {
        validate : function(code){
            return code === "abcdef";
        },
        msg : "验证码不对"
    };

    validate.check(data);

    if(validate.msg.length){
        console.log(validate.msg.join("
"));
    }
原文地址:https://www.cnblogs.com/mr189/p/3964489.html