设计模式学习笔记(2)——命令模式

命令模式:将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其它对象。

命令对象:通过在特定接收者上绑定一组动作来封装一个请求。要达到这一点,命令对象将动作和接收者包进对象中,只暴露出一个execute()方法,这方法被调用的时候,接收者就会执行这些动作。

  1. 实现命令接口(所有的命令对象都必须实现这一接口)

1 public interface Command {
2 
3 public void execute();
4 
5 }
View Code

      2.实现一个打开电灯的命令(继承命令接口)

 1   public class Ligth {
 2 
 3             public void on(){
 4 
 5                 //开灯
 6 
 7             }
 8 
 9             public void off(){
10 
11                 //关灯
12 
13             }
14 
15 }
View Code
 1 public class LightOnCommand implements Command {
 2 
 3             Ligth light;
 4 
 5         public LightOnCommand(Ligth light){
 6 
 7             this.light=light;
 8 
 9         }
10 
11         @Override
12 
13         public void execute() {
14 
15             // TODO Auto-generated method stub
16 
17             light.on();
18 
19         }
20 
21 }
View Code

  3.使用命令对象

  假设有一个插槽,该插槽有就只有一个命令。

 1 public class SimpleRemoteControl {
 2 
 3             Command slot;
 4 
 5  
 6 
 7             public void setCommand(Command command) {
 8 
 9                 this.slot = command;
10 
11             }
12 
13             public void buttonWasPressed(){
14 
15                 slot.execute();
16 
17             }
18 
19 }
View Code

        说明:

  •       SimpleRemoteControl就是一个调用者,会传入一个命令对象,可以用来发出请求
  •              Light就是请求的接收者
  •              LightOnCommand命令对象,需要将接收者传给它
  •              调用者就可以设置命令,然后执行按钮
 1  public static void main(String[] args) {
 2 
 3         //创建一个调用者
 4 
 5         SimpleRemoteControl remote=new SimpleRemoteControl();
 6 
 7         //创建一个接收者
 8 
 9         Light light=new Light();
10 
11         //创建一个命令,将接收者传给它
12 
13         LightOnCommand lightOn=new LightOnCommand(light);
14 
15         //执行调用者(1.设置命令,2.打开按钮)
16 
17         remote.setCommand(lightOn);
18 
19         remote.buttonWasPressed();
20 
21     }
View Code
posted @ 2016-12-13 15:48  求学之道  阅读(254)  评论(0编辑  收藏  举报