美文网首页
命令模式(Command)(常用)

命令模式(Command)(常用)

作者: jiahzhon | 来源:发表于2019-10-02 13:18 被阅读0次

    在软件开发系统中,常常出现“方法的请求者”与“方法的实现者”之间存在紧密的耦合关系。这不利于软件功能的扩展与维护。例如,想对行为进行“撤销、重做、记录”等处理都很不方便,因此“如何将方法的请求者与方法的实现者解耦?”变得很重要,命令模式能很好地解决这个问题。

    在现实生活中,这样的例子也很多,例如,电视机遥控器(命令发送者)通过按钮(具体命令)来遥控电视机(命令接收者),还有计算机键盘上的“功能键”等。

    定义:
    将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。

    使用场景:

    • 当系统需要将请求调用者与请求接收者解耦时,命令模式使得调用者和接收者不直接交互。
    • 当系统需要随机请求命令或经常增加或删除命令时,命令模式比较方便实现这些功能。
    • 当系统需要执行一组操作时,命令模式可以定义宏命令来实现该功能。
    • 当系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作时,可以将命令对象存储起来,采用备忘录模式来实现。

    结构:

    1. 抽象命令类(Command)角色:声明执行命令的接口,拥有执行命令的抽象方法 execute()。
    2. 具体命令角色(Concrete Command)角色:是抽象命令类的具体实现类,它拥有接收者对象,并通过调用接收者的功能来完成命令要执行的操作。
    3. 实现者/接收者(Receiver)角色:执行命令功能的相关操作,是具体命令对象业务的真正实现者。
    4. 调用者/请求者(Invoker)角色:是请求的发送者,它通常拥有很多的命令对象,并通过访问命令对象来执行相关请求,它不直接访问接收者。


      11.png

    代码:

    public class CommandPattern
    {
        public static void main(String[] args)
        {
            Command cmd=new ConcreteCommand();
            Invoker ir=new Invoker(cmd);
            System.out.println("客户访问调用者的call()方法...");
            ir.call();
        }
    }
    //调用者
    class Invoker
    {
        private Command command;
        public Invoker(Command command)
        {
            this.command=command;
        }
        public void setCommand(Command command)
        {
            this.command=command;
        }
        public void call()
        {
            System.out.println("调用者执行命令command...");
            command.execute();
        }
    }
    //抽象命令
    interface Command
    {
        public abstract void execute();
    }
    //具体命令
    class ConcreteCommand implements Command
    {
        private Receiver receiver;
        ConcreteCommand()
        {
            receiver=new Receiver();
        }
        public void execute()
        {
            receiver.action();
        }
    }
    //接收者
    class Receiver
    {
        public void action()
        {
            System.out.println("接收者的action()方法被调用...");
        }
    }
    

    例子:
    实现一个遥控器,可以控制电灯的开或者关。

    package Command;
    
    public interface Command {
        public void execute();
    }
    
    public class Light {
        public void on() {
            System.out.println("light up");
        }
    
        public void off() {
            System.out.println("douse the glim");
        }
    }
    
    public class LightOnCommand implements Command{
        Light light;
    
        public LightOnCommand(Light light) {
            this.light = light;
        }
    
        public void execute() {
            light.on();
        }
    }
    
    public class SimpleRemoteControl {
        Command slot;
    
        public SimpleRemoteControl() {}
    
        public void setCommand(Command command) {
            this.slot = command;
        }
    
        public void buttonWasPressed() {
            slot.execute();
        }
    }
    

    测试类

    public class Main {
    
        public static void main(String[] args) {
    
            SimpleRemoteControl remote = new SimpleRemoteControl();
            Light light = new Light();
            LightOnCommand lightOn = new LightOnCommand(light);
    
            remote.setCommand(lightOn);
            remote.buttonWasPressed();
    
        }
    }
    

    应用场景:
    线程池、队列请求、记录宏 。。。

    • 在Java线程池中,线程的调度基于生产者消费者模式,所以往往在内部会实现一个阻塞队列。可以在一端添加任务,另一端消费任务。同时任务和工作队列之前是解耦的,无论传入什么任务给线程池,工作队列只负责取出任务,执行execute()方法,下一个…
    20180313205732595.png
    • receiver
    public class DatabaseOp {
    
        public void add() {
            System.out.println("向数据库添加数据");
        }
    
        public void delete() {
            System.out.println("向数据库删除数据");
        }
    
        public void update() {
            System.out.println("向数据库更新数据");
        }
    
    }
    
    public class FileOp {
    
        public void upload() {
            System.out.println("文件上传");
        }
    
        public void download() {
            System.out.println("文件下载");
        }
    
        public void md5() {
            System.out.println("对文件进行md5加密");
        }
    
    }
    
    public class ScoketOp {
    
        public void send() {
            System.out.println("向网络中发送数据");
        }
    
        public void receive() {
            System.out.println("从网络中接收数据");
        }
    
    }
    
    
    • Command
    public interface Command {
        //简化操作,不带参数
        void execute();
    }
    
    • concreteCommand
    public class DbAdd implements Command {
    
        DatabaseOp op;
    
        public DbAdd(DatabaseOp op) {
            this.op = op;
        }
    
        @Override
        public void execute() {
            op.add();
        }
    
    
    }
    
    public class FileDownload implements Command {
    
        FileOp op;
    
        public FileDownload(FileOp op) {
            super();
            this.op = op;
        }
    
        @Override
        public void execute() {
            op.download();
        }
    
    
    }
    
    • Invoker
    public class SchedulerControl {
    
        Queue<Command> queue = new LinkedList<Command>();
    
        public void setScheduler(Command command) {
            queue.add(command);
        }
    
        //开启多线程
        public void startComand() throws Exception {
            Command command = queue.poll();
            while (command != null) {
                ThreadUtils.startThread(command);
                command = queue.poll();
            }
        }
    
    }
    
    • 线程辅助类
    public class ComandThread implements Runnable {
    
        Command command;
    
        public ComandThread(Command command) {
            this.command = command;
        }
    
        @Override
        public void run() {
            System.out.println(command.getClass() + "开始");
            //随机延时 1到10秒,模拟任务需要很久的时间
            int nextInt = new Random().nextInt(10);
            try {
                Thread.sleep(nextInt * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            command.execute();
    
            System.out.println(command.getClass() + "结束, 共用时" + nextInt + "秒");
        }
    
    }
    
    • Invoker
    public class ThreadUtils {
    
        //开启多线程
        public static void startThread(Command command) throws Exception {
            ComandThread target = new ComandThread(command);
            Thread thread = new Thread(target);
            thread.start();
        }
    
    }
    
    • 测试
    public class DriveTest {
    
        public static void main(String[] args) throws Exception {
    
            //Receiver
            DatabaseOp databaseOp = new DatabaseOp();
            FileOp fileOp = new FileOp();
            ScoketOp scoketOp = new ScoketOp();
    
            //concreteCommand
            DbAdd dbAdd = new DbAdd(databaseOp);
            FileDownload fileDownload = new FileDownload(fileOp);
            FileUpload fileUpload = new FileUpload(fileOp);
            ScoketReceive scoketReceive = new ScoketReceive(scoketOp);
    
            //Invoker绑定concreteCommand
            SchedulerControl control = new SchedulerControl();
            control.setScheduler(dbAdd);
            control.setScheduler(fileUpload);
            control.setScheduler(fileDownload);
            control.setScheduler(scoketReceive);
            //再次向数据库插入数据
            control.setScheduler(dbAdd);
    
            //开启工作队列
            control.startComand();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:命令模式(Command)(常用)

          本文链接:https://www.haomeiwen.com/subject/ewalpctx.html