6、命令模式

1、特点

命令模式是最简单和优雅的模式之一,命令模式中的命令(command)指的是一个执行某些特定事情的指令。命令模式最常见的应用场景是:有时候需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。此时希望用一种松耦合的方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。

2、demo

菜单程序

var bindClick = function(button, func) {
    button.onclick = func;
};
var MenuBar = {
    refresh: function() {
        console.log('刷新菜单界面');
    }
};
var SubMenu = {
    add: function() {
        console.log('增加子菜单');
    },
    del: function() {
        console.log('删除子菜单');
    }
};
bindClick(button1, MenuBar.refresh);
bindClick(button2, SubMenu.add);
bindClick(button3, SubMenu.del);

小球在平面上的移动

<html>

<body>
    <p>是让页面上的小球移动到水平方向的某个位置。现在页面中有一个input 文本框和一个button 按钮,文本框中可以输入一些数字,表示小球移动后的水平位置,小球在用户点击按钮后立刻开始移动</p>
    <div id="ball" style="position:absolute;background:#000;width:50px;height:50px"></div>
    输入小球移动后的位置:<input id="pos" />
    <button id="moveBtn">开始移动</button>
    <button id="cancelBtn">cancel</cancel> <!--增加取消按钮-->
</body>
<script>
    //设计模式的主题总是把不变的事物和变化的事物分离开来。
    var ball = document.getElementById('ball');
    var pos = document.getElementById('pos');
    var moveBtn = document.getElementById('moveBtn');
    var cancelBtn = document.getElementById('cancelBtn');

    var MoveCommand = function(receiver, pos) {
        this.receiver = receiver;
        this.pos = pos;
        this.oldPos = null;
    };

    MoveCommand.prototype.execute = function() {
        this.receiver.start('left', this.pos, 1000, 'strongEaseOut');
        this.oldPos = this.receiver.dom.getBoundingClientRect()[this.receiver.propertyName];
        // 记录小球开始移动前的位置
    };

    MoveCommand.prototype.undo = function() {
        this.receiver.start('left', this.oldPos, 1000, 'strongEaseOut');
        // 回到小球移动前记录的位置
    };

    var moveCommand;
    moveBtn.onclick = function() {
        var animate = new Animate(ball);
        moveCommand = new MoveCommand(animate, pos.value);
        moveCommand.execute();
    };
    cancelBtn.onclick = function() {
        moveCommand.undo(); // 撤销命令
    };
</script>

</html>

参考文献:参考文献:《JavaScript设计模式与开发实践》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值