【设计模式】命令模式

导读:本篇文章讲解 【设计模式】命令模式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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

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

先看一个例子,设计一个家电遥控器的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.bmabk.com/index.php/post/13288.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!