来自 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 图如下图所示。
看看这段代码:
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());
}
}
- ThreadCommand 是Client
- Runnable 界面是Command
- MyRunnable 是 ConcreteCommand
- Thread 是 Invoker,使用
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)给名为 Receiver
和 Account
的显式接收者的示例。
关于带有 Runnable 类 : Is Receiver missing? 的 java 命令模式示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610215/