🧩 OOP Concepts Intermediate

What is the Command pattern?

Why Interviewers Ask This

Mid-level OOP Concepts roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

The Command pattern encapsulates a request as an object, allowing parameterization of clients with different requests, queuing of requests, logging, and supporting undoable operations. Core structure: interface Command { void execute(); void undo(); } class TextEditor { private StringBuilder text = new StringBuilder(); private Deque<Command> history = new ArrayDeque<>(); public void executeCommand(Command command) { command.execute(); history.push(command); } public void undo() { if (!history.isEmpty()) { history.pop().undo(); } } public String getText() { return text.toString(); } // Accessor for commands: public StringBuilder getBuffer() { return text; } } class InsertTextCommand implements Command { private TextEditor editor; private String textToInsert; private int position; public InsertTextCommand(TextEditor editor, String text, int pos) { this.editor = editor; this.textToInsert = text; this.position = pos; } @Override public void execute() { editor.getBuffer().insert(position, textToInsert); } @Override public void undo() { editor.getBuffer().delete(position, position + textToInsert.length()); } } // Usage: TextEditor editor = new TextEditor(); editor.executeCommand(new InsertTextCommand(editor, "Hello", 0)); editor.executeCommand(new InsertTextCommand(editor, " World", 5)); System.out.println(editor.getText()); // "Hello World" editor.undo(); System.out.println(editor.getText()); // "Hello". Command queue (task scheduling): store commands in a queue, execute asynchronously. Macro recording: record a list of commands, replay them. Transaction log: log commands to disk, replay after crash. Real uses: GUI button actions, undo/redo in editors, job queues, database transaction logs, game input recording.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last OOP Concepts project, I used this when...' immediately makes your answer more credible and memorable.