330 likes | 594 Views
Learn about Chain of Responsibility, Command, Interpreter, and Iterator patterns in object-oriented design. Discover how these patterns help in managing object responsibilities, request handling, language grammar interpretation, and list traversal.
E N D
Behavioral Design Patterns Joe Komar Komar Associates
Behavioral Patterns • Concerned with algorithms and the assignment of responsibilities between objects • Include patterns of communications among objects Komar Associates
Chain 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 don’t know which object will handle the request or don’t want to specifically identify the handler • Often implemented as linked lists of objects Komar Associates
Chain 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 don’t know which one until run time Komar Associates
Command • Encapsulate a request as an object • Object encapsulates all the information needed to call a method at a later time • 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 Komar Associates
Command Example Output Komar Associates
Command Example Code abstract class Command { abstract public void Execute(); } Komar Associates
Command 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); } } //=-=-=-=-=-=-=-=-=-=-=-= Komar Associates
Command 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); } } Komar Associates
Command 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(); } } Komar Associates
Command 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; } } //Calls MenuItem constructor Komar Associates
Command Example Code static public void main(String argv[]) { new MenuComd(); } Komar Associates
Command 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; Komar Associates
Command 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); Komar Associates
Command 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); Komar Associates
Command 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); } Komar Associates
Command 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(); } Komar Associates
Command Example Output Komar Associates
Interpreter • Define a representation for a language’s 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 (i.e. composite pattern) Komar Associates
Iterator • 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 Komar Associates
Iterator • 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. Komar Associates
Mediator • 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 Komar Associates
Mediator Komar Associates
Mediator 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); Komar Associates
Memento • Without violating encapsulation, capture and externalize an object’s internal state • Objective is to restore to this state at a later time • checkpoints • error recover • rollback • undo Komar Associates
Observer • 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 Komar Associates
State • Object alters behavior when its internal state changes • As for finite state machines • 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 Komar Associates
Strategy • Define a family of algorithms and encapsulate each one creating a separate class hierarchy structure for the algorithms • Like an image processing package needs to keep the image type separate from the 100+ available algs • Use when: • class defines many behaviors appearing as multiple conditional statements • algorithms use data that clients shouldn’t see • need different variants on an algorithm • class seems to need way too many methods Komar Associates
Template • Define the skeleton of an algorithm, deferring some steps to subclasses • Lets subclass define certain steps in the algorithm without changing the algorithm’s structure • Done with “template methods” that use abstract methods defined in subclasses Komar Associates
Visitor • Create objects that contain operations common across many objects in a class structure • Way of separating an algorithm from an object structure upon which it operates • Visitor object is passed to the client object and used to perform an operation • Useful when there are some common operations and don’t want to change the client interfaces to accommodate • Result is the ability to add new operations to existing object structures without modifying those structures Komar Associates
Design 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 • Also read wikipedia for “<name> pattern” • Don’t be discouraged!! Komar Associates