Ravindra babu Ravindra babu - 1 month ago 8
Java Question

java command pattern example with Runnable class : Is Receiver missing?

From Examples of GoF Design Patterns in Java's core libraries question, it was quoted that


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


As per my understanding of Command pattern,

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

Have a look at this working example

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

enter image description here

Have a look at this code:

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 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)



Is Receiver missing here? Or Does MyRunnable play combined role of ConcreteCommand and Receiver?

Answer

The receiver is a relic of C/C++ in which the method to be invoked is separated from the object to invoke it on. You could implement that behavior in Java by passing a method using reflection; but as you guessed, the more idiomatic Java approach is to treat the concrete command and receiver as one object.