Description on wiki is here
Important Points on Command Pattern
- Command pattern helps to decouple the invoker and the receiver. Receiver is the one which knows how to perform an action.
- Command helps to implement call back in java.
Helps in terms of extensibility as we can add new command without changing existing code.
- Command defines the binding between receiver and action.
- A command should be able to implement undo and redo operations. That is restting the state of the receiver. It can be done from the support of receiver.
Command Pattern in Java API
Implementations of java.lang.Runnable and javax.swing.Action follows command design pattern , and as @Dave Newton said They're pretty good examples
.Then you don't need to find out another much better examples in the java api .
Example
I have an example about using runnable with swing. In the code below Runnable object (command) is send to a method as argument and can be invoked at any time.
Runnable runnable = new Runnable() {
@Override
public void run() {
this.label.setText("Updated text");
}
};
SwingUtilities.invokeLater(runnable);
Summary
The command pattern is a powerful and flexible design idiom, commonly used in Graphical User Interface design to handle events and commands issued by a user. Design patterns are intended to allow greater modularity when designing programs, reducing the dependencies placed on any given block of code.
Practise Exercise
Using the command pattern , Create a small app which simulates a simple calculator, with operations such as add, subtract and multiply.