What is Command pattern?
In object oriented world we talk in terms of objects. In simple words we send some request to some objects. With Command Pattern we can encapsulate request as an object.
Why we store the request/action as an object?
By doing so we get power of playback. Repeat the same request any time we want without much effort. Also if required we can undo it.
Can you provide an example for command pattern?
Best example is Menu system where each menu (such as File, Edit represents separate command).
What are the components involved in Command pattern?
- Receiver – Who, on request will do something? (It will be many)
- Actual Command – Which will make request to receiver on demand.(It will be many too)
- Invoker – Holds all the commands in sequence (or randomly) and acts as a bridge between Actual Command and client.
Can you tell me some specific advantages?
- Because every action or request is handled by a separate class SRP – Single responsibility is obeyed.
- Because every action/request go via Invoker, maintaining queue of all the requests is easy now and if required we can re-invoke in the same or reverse (Undo) in future.
One of the most asked design pattern interview question is around factory patterns , please do the see the below video for the same.