What is the Command pattern and how does it encapsulate requests?

The Command pattern is a behavioral pattern that encapsulates a request as a standalone object, so the action, its parameters, and its receiver are all bundled together and can be passed around, queued, logged, or undone like any other object.

Key Points: • A Command interface typically declares an execute() method, and optionally an undo() method. • Each concrete command wraps a receiver and the specific action to invoke on it. • The invoker that triggers the command doesn't need to know what the command actually does. • Because a request becomes an object, it can be stored in a queue, logged for auditing, or reversed via undo. • It decouples the object that issues a request from the object that performs it.

Example: A text editor's undo stack works by storing executed Command objects; each command knows both how to redo its action and how to reverse it, so pressing undo just calls the last command's undo() method.

Interview Tip: A concise interview answer is:

"Command encapsulates a request as an object with an execute() method, bundling the action and its receiver together, which decouples the sender from the actual execution logic and makes it easy to queue, log, or undo operations since each request is just an object you can store and pass around."