Command Pattern Demo

Command Interface

package CommandPatternDemo; // Command interface interface Command { void execute(); }
package CommandPatternDemo; class CopyCommand implements Command { private TextEditor textEditor; public CopyCommand(TextEditor textEditor) { this.textEditor = textEditor; } public void execute() { textEditor.copy(); } }
package CommandPatternDemo; // Concrete commands class CutCommand implements Command { private TextEditor textEditor; public CutCommand(TextEditor textEditor) { this.textEditor = textEditor; } public void execute() { textEditor.cut(); } }

Driver:

In this example, the Command pattern is used to implement the functionality of a text editor toolbar. The Command interface defines the execute() method, and there are concrete command classes like CutCommand, CopyCommand, and PasteCommand that implement the Command interface.

The TextEditor class is the receiver, which knows how to perform the actual operations of cutting, copying, and pasting text. The Toolbar class acts as the invoker, which holds references to the concrete commands and calls their execute() methods when toolbar buttons are pressed. The Main class represents the client that sets up the text editor, creates the commands, and associates them with the toolbar.

By using the Command pattern, the toolbar buttons are decoupled from the specific text editor operations. The toolbar invokes the commands without knowing the receiver's implementation details. This allows for easy extensibility, as new commands can be added without modifying the existing toolbar or the receiver. The Command pattern also facilitates logging, queuing, and undo/redo functionalities.