【设计模式】命令模式

命令模式的核心是把方法调用封装起来,调用的对象不需要关心是如何执行的。

定义:命令模式将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也可以支持撤销操作。

先看一个例子,设计一个家电遥控器的API,可以通过遥控器发出命令来控制不同生产商生产的家电,比如关灯、开灯。

以下是一个简单的代码示例。

 1 package cn.sp.test05;
 2 /**
 3  * 电灯类
 4  * @author 2YSP
 5  *
 6  */
 7 public class Light {
 8     
 9     public void on(){//打开
10         System.out.println("light is on");
11     }
12     
13     public void off(){//关闭
14         System.out.println("light is off");
15     }
16 }
 1 package cn.sp.test05;
 2 /**
 3  * 命令接口
 4  * @author 2YSP
 5  *
 6  */
 7 public interface Command {
 8     
 9     public void execute();
10 }
 1 package cn.sp.test05;
 2 
 3 public class LightOnCommand implements Command {
 4 
 5     Light light ; 
 6     
 7     public LightOnCommand(Light light){
 8         this.light = light;
 9     }
10     
11     @Override
12     public void execute() {
13         //调用其方法
14         light.on();
15     }
16 
17 }
 1 package cn.sp.test05;
 2 /**
 3  * 简单的遥控器类
 4  * @author 2YSP
 5  *
 6  */
 7 public class SimpleRemoteControl {
 8     Command slot;
 9 
10     public SimpleRemoteControl() {
11     }
12     
13     public void setCommand(Command command){
14         this.slot = command;
15     }
16     //按下按钮调用执行方法
17     public void buttonWasPressed(){
18         slot.execute();
19     }
20 }
 1 package cn.sp.test05;
 2 /**
 3  * 设计模式之命令模式
 4  * @author 2YSP
 5  *
 6  */
 7 public class RemoteControlTest {
 8 
 9     public static void main(String[] args) {
10         SimpleRemoteControl simpleRemoteControl = new SimpleRemoteControl();
11         Light light = new Light();
12         //命令还是得靠 电灯自己完成
13         LightOnCommand lightOn = new LightOnCommand(light);
14         //设置命令
15         simpleRemoteControl.setCommand(lightOn);
16         //执行
17         simpleRemoteControl.buttonWasPressed();
18     }
19 
20 }

运行main方法,输出light is on.

今天才发现线程池用到了这个模式。。。。

更多详细请参考Head First 设计模式。

原文地址:https://www.cnblogs.com/2YSP/p/6921347.html