Command and Iterator Patterns
Encapsulate requests as objects with Command and traverse collections with Iterator.
What is the Command Pattern?
The Command Pattern is a behavioral design pattern that turns a request into a stand-alone object. This object contains all information about the request, including the method to call and the parameters it needs.
Think of it like putting an instruction into a package. You can then pass this package around, queue it, or even undo it later, without the sender needing to know how the instruction is carried out.
Core Components of Command
To understand the Command Pattern, let's look at its key players:
- Command: An interface or abstract class declaring an
execute()method. - ConcreteCommand: Implements the
Commandinterface, binding a specific Receiver object to an action. - Receiver: The object that performs the actual work. It knows how to carry out the operation.
- Invoker: Asks the command to carry out its request. It doesn't know the specifics of the operation or the receiver.
- Client: Creates a
ConcreteCommandobject and sets itsReceiver.
All lessons in this course
- Observer and Strategy Patterns
- Command and Iterator Patterns
- Template Method and State Patterns
- Mediator and Chain of Responsibility