gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:24:57 25 4
gpt4 key购买 nike

来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com