模式学习(六)--- 策略模式

var validator = {
        // 所有可用的检查类型
        types : {},

        // 在当前验证绘画中的错误消息
        message : [],

        // 当前验证配置
        config : {},

        // 接口方法
        validate : function(data){
            var i, msg, type, checker, result_ok;

            // 重置所有消息
            this.message = [];

            for(i in data){
                if(data.hasOwnProperty(i)){
                    type = this.config[i];
                    console.log("types are:",this.types)
                    checker = this.types[type];// 每种检查的方法

                    if(!type){
                        continue;// type不存在则跳出本次循环
                    }

                    if(!checker){// 要是不存在检查方法抛出错误
                        throw{
                            name : "ValidationError",
                            message : "No handler to validate type" + type
                        };
                    }

                    result_ok = checker.validate(data[i]);// 检查的返回结果  : true  false  false 
                    
                    if(!result_ok){
                        msg = "Invalid value for *" + i + "*, " + checker.instructions;
                        this.message.push(msg);
                    }
                }
            }
            return this.hasError();
        },

        // 帮助程序
        hasError : function(){
            return this.message.length !== 0;
        }
    };

    // validator 配置
    validator.config = {
        first_name : 'isNonEmpty',
        age : 'isNumber',
        username : 'isAlphaNum'
    };

    
    // validator的各种检查
    // 非空值得检查
    validator.types.isNonEmpty = {
        validate : function(value){
            return value !== "";
        },
        instructions : "the value cannot be empty"
    };

    // 检查是否是一个数字
    validator.types.isNumber = {
        validate : function(value){
            return !isNaN(value)
        },
        instructions : "the value can only be a valid number, e.g. 1, 3.14 or 2010"
    };

    // 检查该值是否只包含字母和数字
    validator.types.isAlphaNum = {
        validate : function(value){
            return !/[^a-z0-9]/i.test(value);// i : 表示不区分大小写 
        },
        instructions : "the value can only contain characters and numbers, no special symbols"
    };


    var data = {
        first_name : "Super",
        last_name : "Man",
        age : "unknown",
        username : "o_0"
    };
    validator.validate(data);// 验证
    if(validator.hasError()){// 如果有错误, 输出
        console.log(validator.message.join("\n"));
    }

策略模式支持在运行时选择算法。上面是使用策略模式解决表单验证的问题。

posted @ 2013-12-26 18:51  楚玉  阅读(189)  评论(0编辑  收藏  举报