设计模式学习(五)------Command

命令模式:
    -----主题: ****封装调用*****
什么是命令模式??
    是指,将行为的调用者(invoker)和执行者(receiver)解耦(通过组合),因此可以根据功能来使用不同的调用,而不需
了解具体的实现。

餐厅事件:
    1. 顾客点餐,服务员在订单上记录
    2. 服务员,pass的order to the chief
    3. chief cook by the order
这里,我们看到三种对象: client , invoker(服务员) , receiver(chief)
invoker.orderup() // pass the order to the receiver
see here:envolope the request to the order object

so the first step of the Command Model is:
    1. get the request Object

在遥控器例子中,每个按钮赋一个Command , every command has a execute() to 执行行为
一个遥控器有多个按钮,我们可以把它看成一组 Command API
the second step of the Command Model is :
    2. consist a group of the command to an API

public interface Command {
    void execute();
}

每个特定的类型的动作,都设置一个相应的command
eg: 电灯Light
    LightOn inplements Command{
    public void execute(){
        ...//so the job;
    }
这里执行,需要Light 对象( 也就是receiver)(how ??)
组合
set the Light into to the Command
the Command has a Light Object
public class Light{
    ....
}
public LightOn implements Command{
    private Light light;
    public void setLight(Light light){
        this.light = light;
    }
    ...
}

Finally , set the Command Object into the Controler , so you can test!!
public class Controler {
    private Command command;
    public void setCommand(Command command){
        this.command = command;
    }
    public static void main(String[] args){
        ...
    }
}
//这里是个单命令的Controler,当然你也可以包含多个(array, list ,set..)

在其中加入undo()
在Command中加入,undo()
记录command上一步的动作(记录日志的用法,使用堆栈来达到目的)

命令模式的解释:
    将请求封装成对象,这可以让你使用不同的请求,队列,或者日志请求来参数化其他对象。命令模式可以支持撤销

宏命令:
    将多个Command封装在一个Command中,按步骤顺序执行的命令




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值