Directly from Wikipedia:
The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
Edit
After re-reading the Gang of Four's section on the Command pattern, I thought up a better scenario. Let's say you have a GUI library, which defines the following:
public interface Command {
public void execute();
}
public class Button {
private Command command;
public Button(Command command) {
this.command = command;
}
public void click() {
command.execute();
}
}
The Button, in this case, is the receiver of a command, and your code, that creates actual instances of Buttons, is the client. Of course, when you create a button, you have to define some concrete implementations of the Command
interface. But the GUI library does not need to know about these classes; all it needs is the interface. This is how the GUI code is decoupled from your code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…