小白学设计模式之装饰者模式

什么是装饰者模式?

装饰者模式:在不改变原对象的基础上,通过对其进行 包装拓展,使原有对象可以满足用于的更复杂的需求

例子解释

通过一个不断改进输入框的需求来解释装饰者模式

代码

/** 原需求:用户输入密码的时候显示提示文本校验*/

var password_input = document.getElementById('password');
password_input.oninput = function({target}) {
    if(target.value.length < 6) {
        document.getElementById('tip').style.display = "block";
    }else {
        document.getElementById('tip').style.display = "none";
    }
}

/**新需求:需要添加提示文字颜色为红色 */

/* 采用装饰者模式*/

var decorator = function(element_id,fn) {
    var element = document.getElementById(element_id);
    if(typeof element.oninput === 'function') { 
        // 如果存在,缓存原有事件函数;
        var oldInputFunction = element.oninput;
        element.oninput = function(event) {
            // 原函数
            oldInputFunction(event);
            // 新函数
            fn(event);
        }
    }else{
        element.oninput = fn;
    }
}

/**提示文字红色 */
decorator('password',function({target}) {
        document.getElementById('tip').style.color = "#ff0000";
});

/**提示文字用正楷 */
decorator('password',function({target}) {
        document.getElementById('tip').style.fontFamily = "楷体";
});


代码

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容