• 细品 javascript 设计模式(代理模式)


    我尽量用最少的文字,最少的篇幅,讲明白设计模式的方方面面。
    全文连接

    理解代理模式

    为某个对象提供一个替代品,以便控制对他的访问。
    

    举个例子:

    你要提交辞职报告给老板,可是老板今天不在公司。
    那就只能给老板的秘书,等老板什么时候回公司了替你提交给他。

    上代码:秘书替你递交辞职报告

    // 员工
    let workers = {
        sendReport: function(target) {
            // 提交给老板
            target.receiveFile({
                title: '辞职报告'
            })
        }
    }
    
    // 老板
    let boss = {
        receiveFile: function(report) {
            console.log('老板收到 ', report);
            this.approval(report);
        },
        approval: function(report) {
            console.log('通过: ', report);
        },
        state: 'out', // 老板出去了
    }
    
    // 秘书
    let secretary = {
        receiveFile: function(report) {
            let timer = null;
            let sendBoss = function() {
                if (boss.state === 'in') {
                    console.log('提交给老板', report);
                    boss.receiveFile(report);
                    clearInterval(timer);
                } else {
                    console.log('老板不在,再等等');
                }
            }
            timer = setInterval(sendBoss, 2e3);
        }
    }
    // 先把辞职信提交给老板秘书。
    workers.sendReport(secretary);
    

    在这个例子中,秘书就是你的代理。你总不能一直在老板办公室的门口等,这是不合适的。

    对应程序中,代理更好的诠释了面向对象设计中单一职能原则。一个类只做一件事。
    代理 和 对象 组合起来使用,显然会降低程序中的耦合度。
    

    保护代理和虚拟代理

    用上面那个例子来解释

    保护代理:

    你把辞职报告交给秘书,秘书一看是辞职报告直接给你退了回去。她说你得找你的上级领导签字,然后在交给老板
    
    这就是保护代理,它的目是保护被代理人
    

    虚拟代理:

    老板的秘书是一个机器人,外观和老板一样。你把辞职报告给他,它等 boos 本体回来了再交给本体
    
    虚拟代理的接口和被代理的对象是一样的,这是虚拟代理的最大特点。方便代替其他对象做一些事情。重要的是调用者感知不到
    

    其他例子

  • 相关阅读:
    Swift基础学习
    APP的线程安全
    LintCode-O(1) Check Power of 2
    LintCode-Maximum Subarray Difference
    LintCode-Subarray Sum Closest
    LintCode-Rehashing
    Lintcode-Max Tree
    LintCode-Interleaving Positive and Negative Numbers.
    LintCode-Topological Sorting
    LintCode-Rotate String
  • 原文地址:https://www.cnblogs.com/shixinglong/p/13173352.html
Copyright © 2020-2023  润新知