1 / 31

Behavioral Design Patterns

Behavioral Design Patterns. Joe Komar. Behavioral Patterns. Concerned with algorithms and the assignment of responsibilities between objects Include patterns of communications among objects. Chain of Responsibility. Gives more than one object a chance to handle a request

bmckenzie
Download Presentation

Behavioral Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Behavioral Design Patterns Joe Komar Komar Associates

  2. Behavioral Patterns • Concerned with algorithms and the assignment of responsibilities between objects • Include patterns of communications among objects Komar Associates

  3. 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

  4. 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

  5. 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

  6. Command Example Output Komar Associates

  7. Command Example Code abstract class Command { abstract public void Execute(); } Komar Associates

  8. 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

  9. 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

  10. 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

  11. 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

  12. Command Example Code static public void main(String argv[]) { new MenuComd(); } Komar Associates

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. Command Example Output Komar Associates

  19. 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

  20. 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

  21. 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

  22. 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

  23. Mediator Komar Associates

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

More Related