Behavioral Patterns: Command Pattern Chain of Responsibility

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

BEHAVIORAL PATTERNS

Command Pattern
Chain of Responsibility
Command pattern is a data driven design
pattern and falls under behavioral
pattern category. A request is wrapped
under an object as command and passed
to invoker object. Invoker object looks
for the appropriate object which can
handle this command and passes the
command to the corresponding object
which executes it.
One example of the command pattern being executed in
the real world is the idea of a table order at a restaurant:
the waiter takes the order, which is a command from the
customer.This order is then queued for the kitchen staff. 
The waiter tells the chef that the a new order has come
in, and the chef has enough information to cook the
meal.
Interface Order acting as a command. Stock class
acts as a request. We have concrete classes
BuyStock and SellStock implementing Order
interface which will do actual command
processing. A class Broker is created which acts as
an invoker object. It can take and place orders.
Broker object uses command pattern to identify
which object will execute which command based
on the type of command.
CommandPatternDemo, , will use Broker class to
demonstrate command pattern.
Stock class acting as request

Order acts as command

invoker
Chain of Responsibility
The chain of responsibility pattern creates
a chain of receiver objects for a request.
This pattern decouples sender and
receiver of a request based on type of
request.
In this pattern, normally each receiver
contains reference to another receiver. If
one object cannot handle the request
then it passes the same to the next
receiver and so on.
Thus, the chain of responsibility is an object
oriented version of the

if ... else if ... else if ....... else ... End if


idiom, with the benefit that the
condition–action blocks can be
dynamically rearranged and reconfigured
at runtime.
This pattern is recommended when either of
the following scenarios occur in your
application:
Multiple objects can handle a request and
the handler doesn't have to be a specific
object
A set of objects should be able to handle a
request with the handler determined at
runtime
A request not being handled is an
acceptable outcome.
We have created an abstract class
AbstractLogger with a level of logging. Then
we have created three types of loggers
extending the AbstractLogger. Each logger
checks the level of message to its level and
prints accordingly otherwise does not print
and pass the message to its next logger.
Extends

You might also like