Runnable类的Java命令模式示例:是否缺少Receiver? [英] java command pattern example with Runnable class : Is Receiver missing?

查看:197
本文介绍了Runnable类的Java命令模式示例:是否缺少Receiver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Java的核心库问题,有人引用

java.lang.Runnable的所有实现都是 Command 模式的示例.

根据我对Command模式的了解,

As per my understanding of Command pattern,

客户端呼叫 Invoker => Invoker 呼叫 ConcreteCommand => ConcreteCommand 调用 Receiver 方法,该方法实现了抽象的 Command 方法.

Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.

看看这个有效的示例

命令模式UML图如下.

Command pattern UML diagram from this article is shown as below.

看看这段代码:

public class ThreadCommand{
    public static void main(String args[]){
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}
class MyRunnable implements Runnable{
    public void run(){
        System.out.println("Running:"+Thread.currentThread().getName());
    }
}

  1. ThreadCommand 客户端
  2. Runnable 界面是 Command
  3. MyRunnable ConcreteCommmand
  4. Thread Invoker ,调用 ConcreteCommand 实现(调用run()方法)的start()方法
  1. ThreadCommand is Client
  2. Runnable interface is Command
  3. MyRunnable is ConcreteCommmand
  4. Thread is Invoker with start() method calling ConcreteCommand implementaiton ( which calls run() method)

这里没有接收方吗?还是MyRunnable扮演ConcreteCommand和Receiver的共同角色?

推荐答案

Receiver 是可选的,具体取决于 ConcreteCommmand 是否拥有要执行的业务逻辑.在本书的第238页中,

A Receiver is optional, depending on whether the ConcreteCommmand owns the business logic to be executed. From page 238 of the book,

命令可以具有多种功能.在一个极端情况下,它仅定义了接收者和执行请求的动作之间的绑定.在另一个极端,它本身实现了所有事情,而没有委托给接收者.

A command can have a wide range of abilities. At one extreme it merely defines a binding between a receiver and the actions that carry out the request. At the other extreme it implements everything itself without delegating to a receiver at all.

在最初的问题中,我们看到一个没有接收器的示例,因为MyRunnable拥有要执行的逻辑.在这里的另外两个答案中,我们看到了委派给名为ReceiverAccount的显式接收器的示例.

In the original question we see an example with no receiver, because MyRunnable owns the logic to be executed. In two other answers here we see examples delegating to explicit receivers named Receiver and Account.

这篇关于Runnable类的Java命令模式示例:是否缺少Receiver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆