Docstoc

State pattern State pattern

Document Sample
State pattern State pattern Powered By Docstoc
					                      State pattern

• Suppose an object is always in one of several
  known states
• The state an object is in determines the behavior
  of several methods
• Could use if/case statements in each method
• Better solution: state pattern



                         CMSC 433, Fall 2002             50




                      State pattern

• Have a reference to a state object
   – Normally, state object doesn’t contain any fields
   – Change state: change state object
   – Methods delegate to state object




                         CMSC 433, Fall 2002             51




                                                              1
Structure of State pattern




         CMSC 433, Fall 2002   52




Instance of State Pattern




         CMSC 433, Fall 2002   53




                                    2
                      State pattern notes

• Can use singletons for instances of each state class
    – State objects don’t encapsulate state, so can be shared
• Easy to add new states
    – New states can extend other states
         • Override only selected functions




                               CMSC 433, Fall 2002              54




           Example – Finite State Machine

class FSM {
      State state;
      public FSM(State s) { state = s; }
      public void move(char c) { state = state.move(c); }
      public boolean accept() { return state.accept();}
   }

   public interface State {
      State move(char c);
      boolean accept();
   }



                               CMSC 433, Fall 2002              55




                                                                     3
                          FSM Example – cont.

class State1 implements State {                    class State2 implements State {
  static State1 instance = new State1();             static State2 instance = new State2();
  private State1() {}                                private State2() {}
  public State move (char c) {                         public State move (char c) {
                                                          switch (c) {
     switch (c) {
                                                             case 'a': return State1.instance;
       case 'a': return State2.instance;                     case 'b': return State1.instance;
       case 'b': return State1.instance;                     default: throw new
       default: throw new                                      IllegalArgumentException();
           IllegalArgumentException();                    }
     }                                                  }
   }                                                 public boolean accept() {return true;}
 public boolean accept() {return false;}           }
}
                                        CMSC 433, Fall 2002                             56




                              Decorator Pattern

   •   Motivation
        – Want to add responsibilities to individual objects, not to an entire class
        – Inheritance requires a compile-time choice
   •   Solution
        – Enclose the component in another object that adds the responsibility
             • The enclosing object is called a decorator.
        – Decorator conforms to the interface of the component it decorates so that
          its presence is transparent to the component's clients.
        – Decorator forwards requests to the component and may perform additional
          actions before or after forwarding.
        – Can nest decorators recursively, allowing unlimited added responsibilities.
        – Can add/remove responsibilities dynamically



                                        CMSC 433, Fall 2002                             57




                                                                                                 4
                      Structure




                        CMSC 433, Fall 2002            58




                 Example: Java I/O

FileReader frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);
String line;
while ((line = lrdr.readLine()) != null) {
  System.out.print(lrdr.getLineNumber() + ":\t" + line);
}




                        CMSC 433, Fall 2002            59




                                                            5
                  Interaction diagram




                          CMSC 433, Fall 2002                  60




          Lexi: Simple GUI-Based Editor

• Lexi is a WYSIWYG editor
   –   supports documents with textual and graphical objects
   –   scroll bars to select portions of the document
   –   be easy to port to another platform
   –   support multiple look-and-feel interfaces
• Highlights several OO design issues
• Case study of design patterns in the design of Lexi


                          CMSC 433, Fall 2002                  61




                                                                    6
                         Design Issues

•   Representation and manipulation of document
•   Formatting a document
•   Adding scroll bars and borders to Lexi windows
•   Support multiple look-and-feel standards
•   Handle multiple windowing systems
•   Support user operations
•   Advanced features
    – spell-checking and hyphenation
                               CMSC 433, Fall 2002           62




           Structure of a Lexi Document

• Goals:
    – store text and graphics in document
    – generate visual display
    – maintain info about location of display elements
• Caveats:
    – treat different objects uniformly
       • e.g., text, pictures, graphics
    – treat individual objects and groups of objects uniformly
       • e.g., characters and lines of text

                               CMSC 433, Fall 2002           63




                                                                  7
          Structure of a Lexi Document

• Solution:
   – define abstract class Glyph for all displayed objects
   – glyph responsibilities:
      • know how to draw itself
      • knows what space it occupies
      • knows its children and parent
   – use recursive composition for defining and handling
     complex objects
   – define composition of Glyph as instances of Glyph

                            CMSC 433, Fall 2002              64




                Glyph Class Diagram




                            CMSC 433, Fall 2002              65




                                                                  8
              The Composite Pattern

• Motivation:
   – support recursive composition in such a way that a
     client need not know the difference between a single
     and a composite object (as with Glyphs)
• Applicability:
   – when dealing with hierarchically-organized objects
     (e.g., columns containing rows containing words …)




                         CMSC 433, Fall 2002                66




                Glyph Class Diagram




                         CMSC 433, Fall 2002                67




                                                                 9
              Composite Pattern (cont’d)

• Consequences:
   – class hierarchy has both simple and composite objects
   – simplifies clients
   – aids extensibility
       • clients do not have to be modified
   – too general a pattern?
       • difficult to to restrict functionality of concrete leaf subclasses




                               CMSC 433, Fall 2002                            68




             Formatting Lexi Documents

• Handle justification, margins, line breaking, etc.
• Many good algorithms exist;
   – different tradeoffs between quality and speed
   – design decision: implement different algorithms, decide at run-time
     which algorithm to use
• Goal: maintain orthogonality between formatting and
  representation (glyphs)
• Solution
   – define root class that supports many algorithms
   – each algorithm implemented in a subclass

                               CMSC 433, Fall 2002                            69




                                                                                   10
          Compositor and Composition

• Relevant design decisions:
   – compositor: class containing formatting algorithm
   – pass objects to be formatted as parameters to
     compositor methods
   – parameters are instances of a Glyph subclass called
     Composition
   – uniform interface between formattable objects and
     compositor algorithms


                         CMSC 433, Fall 2002                 70




          Compositor and Composition

• Relevant design decisions (cont’d):
   – each Composition instance has a reference to a
     compositor object
   – when a composition needs to format itself, it sends a
     message to its compositor instance




                         CMSC 433, Fall 2002                 71




                                                                  11
                    Class Diagram




                          CMSC 433, Fall 2002             72




                   Strategy Pattern

• Name
   – Strategy (aka Policy)
• Applicability
   – many related classes differ only in their behavior
   – many different variants of an algorithm
   – need to encapsulate algorithmic information




                          CMSC 433, Fall 2002             73




                                                               12
           Strategy Pattern: Structure




                           CMSC 433, Fall 2002            74




             Strategy Pattern (cont’d)

• Consequences
  – clear separation of algorithm definition and use
     • glyphs and formatting algorithms are independent
     • alternative (many subclasses) is unappealing
         – proliferation of classes
         – algorithms cannot be changed dynamically
  – elimination of conditional statements
     • as usual with OO programming




                           CMSC 433, Fall 2002            75




                                                               13
             Strategy Pattern (cont’d)

• Consequences (continued)
  – clients must be aware of different strategies
     • when initializing objects
  – proliferation of instances at run-time
     • each glyph has a strategy object with formatting information
     • if strategy is stateless, share strategy objects




                            CMSC 433, Fall 2002                       76




                                                                           14
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:10
posted:5/28/2011
language:English
pages:15