Title: Behavioral Design Patterns
1Behavioral Design Patterns
2Behavioral Patterns
- Concerned with algorithms and the assignment of
responsibilities between objects - Include patterns of communications among objects
3Chain of Responsibility
- Gives more than one object a chance to handle a
request - Chains receiving objects and passes the request
along the chain until it is satisfied - Use when you dont know which object will handle
the request or dont want to specifically
identify the handler - Often implemented as linked lists of objects
4Chain of Responsibility Uses
- Context sensitive Help
- Drawing packages
- Context sensitive mathematical computations
- Any request that might be handled by more than
one object but we dont know which one until run
time
5Command
- Encapsulate a request as an object
- Can then use that object as a parameter
- Often used for things like menu items
- Set up an abstract class with one method
(execute()) - Each menu choice inherits from that and
implements the execute() method
6Command Example Code
abstract class Command abstract public void
Execute()
7Command Example Code
//--------------------------------- // Menu
commands as inner classes // so they can set
variables in this Frame //----------
- class exitCommand extends Command
public void Execute()
System.exit(0)
//-----------
8Command Example Code
class fileCommand extends Command
Frame frm public fileCommand(Frame f)
frm f
//----------------------- public void
Execute() FileDialog fdlg
new FileDialog(frm, "Open a File",
FileDialog.LOAD) fdlg.setVisible(true)
9Command Example Code
class parmCommand extends Command Color
current public parmCommand()
current getBackground() public
void Execute() if (current Color.red)
setBackground(Color.lightGray)
else setBackground(Color.red)
current getBackground() repaint()
10Command Example Code
class commandMenuItem extends MenuItem
private Command comd public
commandMenuItem(String s) super(s)
public void setCommand(Command cmd) comd
cmd public Command getCommand()
return comd
11Command Example Code
static public void main(String argv)
new MenuComd()
12Command Example Code
import java.awt. import java.awt.event. import
java.util. //illustrates using Command
pattern in Menus public class MenuComd extends
Frame implements ActionListener Menu File,
Setup //use derived menu item class which holds
command objects commandMenuItem Open, Exit,
Parameters
13Command Example Code
public MenuComd() super("Menu
Parameters") setBackground(Color.lightGray)
//create the menu bar MenuBar mbar new
MenuBar() setMenuBar(mbar) //put 2
items in the menu bar File new
Menu("File") mbar.add(File) Setup new
Menu("Setup") mbar.add(Setup)
14Command Example Code
//Open menu item calls fileCommand object
Open new commandMenuItem("Open")
Open.setCommand(new fileCommand(this))
File.add(Open) //Exit menu item calls
exitCommand object Exit new
commandMenuItem("Exit") Exit.setCommand(new
exitCommand()) File.add(Exit)
//Parameters menu item calls parmCommand
Parameters new commandMenuItem("Parameters")
Parameters.setCommand(new parmCommand())
Setup.add(Parameters)
15Command Example Code
//all have to listen for action events
Open.addActionListener(this)
Exit.addActionListener(this)
Parameters.addActionListener(this)
setBounds(100, 100, 300, 200)
setVisible(true)
16Command Example Code
public void actionPerformed(ActionEvent e)
Object source e.getSource() //if
this is a menu itme action //we don't even
need to find out which one //just call its
command execute method if(source instanceof
commandMenuItem) ((commandMenuItem)source
).getCommand().Execute()
17Command Example Output
18Interpreter
- Define a representation for a languages grammar
- Define an interpreter to interpret sentences in
the language - If a particular problem occurs frequently enough,
express instances of the problem in a language
and build an interpreter - Often used with compilers
- Uses a tree structure
19Iterator
- Access one element of a list at a time without
exposing its underlying representation - Enumeration class does this
- two methods -- boolean hasMoreElements() and
Object nextElement() - Can go through list once only
- Vector, Hashtable, SequenceInputStream have an
elements() method to return an Enumeration
20Iterator
- Enumeration is good but lacks some handy methods
- Restart to the beginning
- Get the current item again
- Get an item by index number
- Keep two or more lists in sync
- etc.
21Mediator
- Define an object that encapsulates how a set of
objects interact - One place to change code for interacting objects
such as window components - Switchboard whereby every object does not need
to know about every other object
22Mediator
23Mediator Example
gMed new guiMediator() // all of
the event listening takes // place in the
mediator class toBrit.addItemListener(gMed)
toMetric.addItemListener(gMed)
entry.addTextListener(gMed)
Compute.addActionListener(gMed)
Quit.addActionListener(gMed)
24Memento
- Without violating encapsulation, capture and
externalize an objects internal state - Objective is to restore to this state at a later
time - checkpoints
- error recover
- rollback
- undo
25Observer
- Define one-to-many dependence among objects
- When one object changes, all its dependents are
notified and updated - JFC Event listener model
- register listeners
- notify listeners
- unregistered listeners
26State
- Object alters behavior when its internal state
changes - For example, a TCP connection can be idle,
listening, connected, and closed - different methods needed for each such state
- different objects are created based on the
current state of the connection, old objects
abandoned
27Strategy
- Define a family of algorithms and encapsulate
each one creating a separate class hierarchy
structure for the algorithms - Use when
- class defines many behaviors appearing as
multiple conditional statements - algorithms use data that clients shouldnt see
- need different variants on an algorithm
28Template
- Define the skeleton of an algorithm, deferring
some steps to subclasses - Lets subclass define certain steps in the
algorithm without changing the algorithms
structure - Done with template methods that use abstract
methods defined in subclasses
29Visitor
- Create objects that contain operations common
across many objects in a class structure - Visitor object is passed to the client object and
used to perform an operation - Useful when there are some common operations and
dont want to change the client interfaces to
accommodate
30Design Patterns
- Visit the Patterns home page and look around
- Start thinking about your own programs and how
they may represent some patterns - Read a few books, then read them again, then read
them once more - Dont be discouraged!!