3. Review
. What is Behavioral Patterns?
(design patterns that identify common communication patterns between
objects.)
. Chain of Responsibility Pattern?
4. Intent
. encapsulate a request in an object
. allows the parameterization of clients with different requests
. allows saving the requests in a queue
6. Implementation
Classes participating:
- Command: declares an interface for executing an operation.
- ConcreteCommand: extends the Command interface, implementing
the Execute method by invoking the corresponding operations on
Receiver. It defines a link between the Receiver and the action.
- Client: creates a ConcreteCommand object and sets its receiver.
- Invoker: asks the command to carry out the request.
- Receiver: knows how to perform the operations;
8. Implementation
// Client
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();
agent.placeOrder(bsc); // Buy Shares
agent.placeOrder(ssc); // Sell Shares
}
}
9. Problem & Solution
Problem
Need to issue requests to objects without knowing anything about the
operation being requested or the receiver of the request.
Solution
. Requests become first class objects: realized by providing a generic
Command Interface which declares an interface for executing
operations.
. Each concrete Command class stores a reference to it's Receiver as
an instance variable.
10. Benefit
. decouple the invoker and the receiver. Receiver is the one which
knows how to perform an action.
. be able to implement undo and redo operations.
This pattern helps in terms of extensibility as we can add new
command without changing existing code.
11. Drawback
. This pattern ends up forcing a lot of Command classes that will make
your design look cluttered - more operations being made possible leads
to more command classes.
. Intelligence required of which Command to use and when leads to
possible maintenance issues for the central controller.
12. Consequences
. decouples the object that invokes the operation from the one that
knows how to perform it.
. Commands are first-class object
. Composite Commands
. Easy to add new commands
13. When
. parameterized objects depending on the action they must perform
. specifies or adds in a queue and executes requests at different
moments in time
. offers support for undoable actions (the Execute method can
memorize the state and allow going back to that state)
. structures the system in high level operations that based on primitive
operations
. decouples the object that invokes the action from the object that
performs the action. Due to this usage it is also known as Producer
Consumer design pattern.