带有 Runnable 类 : Is Receiver missing? 的 java 命令模式示例

标签 java multithreading design-patterns runnable command-pattern

来自 Examples of GoF Design Patterns in Java's core libraries问题,有人引用

All implementations of java.lang.Runnable are examples of Command pattern.

根据我对命令模式的理解,

Client 调用 Invoker => Invoker 调用 ConcreteCommand = > ConcreteCommand 调用Receiver 方法,该方法实现了抽象的Command 方法

看看这个工作example

来自 this article 的命令模式 UML 图如下图所示。

enter image description here

看看这段代码:

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. ThreadCommandClient
  2. Runnable 界面是Command
  3. MyRunnableConcreteCommand
  4. ThreadInvoker,使用 start() 方法调用 ConcreteCommand 实现(调用 run( ) 方法)

此处是否缺少 Receiver?还是MyRunnable兼具ConcreteCommand和Receiver的作用

最佳答案

Receiver 是可选的,具体取决于 ConcreteCommand 是否拥有要执行的业务逻辑。从书的第 238 页开始,

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 拥有要执行的逻辑。在这里的另外两个答案中,我们看到了委托(delegate)给名为 ReceiverAccount 的显式接收者的示例。

关于带有 Runnable 类 : Is Receiver missing? 的 java 命令模式示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610215/

相关文章:

c++ - C/C++ 中的跨平台线程/静态变量 fork

c# - 控制线程数以平衡 .NET 中的 CPU 和 IO 等待

javascript - 在模块内创建对象 javascript

java - Geotools:将不同样式的点添加到同一 map 图层

java - 构造函数调用是否必须是构造函数中的第一条语句?

c++ - 处理一长串单词。是否可以同时分批处理?

c# - 使用 MVVM 设计模式的应用程序中的 Controller 是什么

java - Hibernate 和 Mysql 结果不匹配

java - XPath:帮助定位使用 HTMLUnit 抓取的 DOM 中的特定元素

java - 游戏的继承/界面设计