命令模式:
-----主题: ****封装调用*****
什么是命令模式??
是指,将行为的调用者(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中,按步骤顺序执行的命令
设计模式学习(五)------Command
最新推荐文章于 2024-04-29 14:32:15 发布