美文网首页
命令模式

命令模式

作者: 柚子过来 | 来源:发表于2018-02-09 11:40 被阅读0次

    作用:将请求的行为封装成对象,这样不同的请求行为过来只要传入对应的command对象就行了,调用者只负责调用execute方法,而不知道具体的行为。

    OO原则:

    封装变化



    Example:
    常用的ExecutorService+Runnable就是命令模式。命令模式一般包括命令接口、具体命令类、执行者类等。Runnable可以看做一个命令接口,它定义了命令的执行行为方法run,我们可以通过实现该接口来定义自己的命令。

    下面我们定义Command命令接口:

    public interface Command {
    void cook();
    }
    

    然后定义自己的命令类:

    public class MyCommand implements Command {
    
    @Override
    public void cook() {
        prepareRice();
        prepareMeat();
        System.out.println("I'm cooking");
    }
    
    public void prepareRice() {
        
    }
    public void prepareMeat() {
        
    }
    }
    

    然后我们需要定义一个执行器暴露给调用者:

    public class MyExecutor {
    private Command command;
    
    public MyExecutor(Command command) {
        this.command = command;
    }
    
    private void execute() {
        this.command.cook();
    }
    }
    

    这样的话如果我们要做米饭和肉怎么办?我们只要new 一个MyCommand对象传给MyExecutor,然后execute就行了:

    public static void main(String[] args) {
        Command command = new MyCommand();
        MyExecutor myExecutor = new MyExecutor(command);
        myExecutor.execute();
    }
    

    跟线程池的做法很像是不是,这样在客户端代码里就不用关心具体的cook行为啦,有新的配方我们就新建 一个对应的Command类就行了,客户端代码还是不变,一如既往的调用execute。

    相关文章

      网友评论

          本文标题:命令模式

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