JavaScript进阶设计模式系列——基础篇——闭包(5)--命令模式的两种实现方式

本文通过一个具体的案例,展示了如何使用面向对象编程和闭包两种不同的方式来实现相同的功能。通过对电视机开关命令的设计模式应用,说明了这两种编程范式的相似之处及不同实现细节。

在面向对象的世界中,过程和数据是一个经常被使用的表达方式。对象,通过方法的形式包含着过程,而闭包则是在过程中以环境的形式包含了数据,因此,只要是用面向对象思想实现的东西,基本上用闭包的思想也能实现。下面,咱们看一则实例,分别使用面向对象形式来实现的写法和使用闭包形式的写法。

面向对象的写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>commandpatern</title>
</head>
<body>
    <button id="execute">click me !</button>
    <button id="undo">click me !</button>

    <script>

        var Tv = {//电视机本身应该具有的方法
            open: function() {
                console.log('open TV !')
            },
            close : function(){
                console.log('close TV !')
            }
        }

        var OpenTvCommand = function(receiver){ //命令对象本身
            this.receiver = receiver;
        }

        OpenTvCommand.prototype.execute = function () {
            this.receiver.open();
        }

        OpenTvCommand.prototype.undo = function () {
            this.receiver.close();
        }

        var setCommand = function (command) {//相当于要遥控器、命令的发出者
            document.getElementById('execute').onclick = function () {
                command.execute();
            }
            document.getElementById('undo').onclick = function () {
                command.undo();
            }
        }

        setCommand( new OpenTvCommand(Tv));

    </script>
</body>

</html>

闭包方式的实现:

var Tv = {
    open: function () {
        console.log('open TV');
    },
    close: function () {
        console.log('close TV');
    }
};

var OpenTvCommand =function (receiver) {//此处不使用立即执行函数的方式,也不需要OpenTVCommand对象自己持有变量,因为receiver这个局部变量会被闭包环境包围,这个局部变量被延续了生命周期
   // this.receiver = receiver;
    var execute = function () {
        receiver.open();
    }

    var undo = function () {
        receiver.close();
    }

    return {
        execute: execute,
        undo: undo
    }

};

var setCommond = function (command) {
    document.getElementById('execute').onclick=function () {
        command.execute();
    }
    document.getElementById('undo').onclick=function () {
         command.undo();
    }
}

setCommond(OpenTvCommand(Tv));//不需要new这个对象,因为OpenTVCommand返回一个对象
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值