• 【设计模式】命令模式


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

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

    先看一个例子,设计一个家电遥控器的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
Copyright © 2020-2023  润新知