Kĩ thuật lập trình - Chapter 5: prototype and system modeling

state pattern: An object whose sole purpose is to represent the current "state" or configuration of another larger object.  A behavioral pattern.  Often implemented with an enum type for the states.  Each object represents one specific state for the larger object.  The larger object sets its state in response to various mutations.  Allows various observers and interested parties to quickly and accurately know what is going on with the larger object's status.

pdf101 trang | Chia sẻ: nguyenlam99 | Lượt xem: 1055 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Chapter 5: prototype and system modeling, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Chapter 5 – Prototype and System Modeling 1 Chapter 5 System modeling Topics covered  Prototyping  UML diagram types 2 Chapter 5 System modeling Big questions  What's the point of prototyping? Should I do it?  If so, when in the overall process or "lifecycle" should I?  Should I make my prototype on paper or digitally?  How do I know whether my UI is good or bad?  What are the ways in which a UI's "quality" can be quantified?  What are some examples of software you use that have especially good/bad UIs? What do you think makes them good/bad? Usability and SW design  Usability: The effectiveness with which users can achieve tasks in a software environment.  studying and improving usability is part of Human-Computer Interaction (HCI)  usability and good UI design are closely related  a bad UI can have unfortunate results... Achieving usability  Some methods to achieve good usability:  user testing / field studies • having users use the product and gathering data  evaluations and reviews by UI experts  card sorting • Show users various UI menus and ask them to group the ones that are similar, to see what UI tasks are seen as being related by users.  prototyping • paper prototyping • code prototyping  Good UI design focuses on the user, not developer or system. Prototyping  prototyping: Creating a scaled-down or incomplete version of a system to demonstrate or test aspects of it.  What are some possible benefits of prototyping?  aids UI design  help discover requirements  help discover test cases and provide a basis for testing  allows interaction with user and customer to ensure satisfaction  team-building Some prototyping methods  UI builders (Visual Studio, etc.)  draw a GUI visually by dragging/dropping UI controls on screen  implementation by hand  writing a "rough" version of your code  paper prototyping: a paper version of a UI Question: Why not just code up a working code prototype?  much faster to create than code  can change faster than code  more visual bandwidth (can see more at once)  more conducive to working in teams  can be done by non-technical people Where does it fit in?  At what point in the software lifecycle should we do (paper) prototyping? When would it be most useful to do it? Why?  We talk about requirements being about "what" and design being about "how." Which is paper prototyping?  PP helps uncover requirements and also upcoming design issues  do PP during or after requirements; before design  "what" vs. "how": PP shows us "what" is in the UI, but it also shows us details of "how" the user can achieve goals in the UI P.P. usability session  user is given tasks to perform using paper prototype  session can be observed by people or camera  one developer can "play computer" Facilitator User “Computer” Observer(s) Schneiderman's 8 Golden Rules • Strive for consistency. • Give shortcuts to the user. • Offer informative feedback. • Make each interaction with the user yield a result. • Offer simple error handling. • Permit easy undo of actions. • Let the user be in control. • Reduce short-term memory load on the user. (from Designing the User Interface, by Ben Schneiderman of UMD, HCI/UI expert) UI design and components  When should we use:  A button?  A check box?  A radio button?  A text field?  A list?  A combo box?  A menu?  A dialog box?  Other..? UI design examples Apple Mac user interfaces UI Hall of Shame  Layout and color Bad error messages UI design - buttons, menus  Use buttons for single independent actions that are relevant to the current screen.  Try to use button text with verb phrases such as "Save" or "Cancel", not generic: "OK", "Yes", "No"  use Mnemonics or Accelerators (Ctrl-S)  tool tips are helpful, but don't rely on them (many users don't know to hover to find them)  Use toolbars for common actions.  Use menus for infrequent actions applicable to many screens.  Users don't like menus! Try not to rely too much on menus.Provide another way to access the same functionality (toolbar, hotkey, etc) Checkboxes, radio buttons  Use check boxes for independent on/off switches (boolean)  Use radio buttons for a small number of related choices, when only one can be activated at a time (enum / constants) Lists, combo boxes, etc.  use text fields (usually with a label) when the user may type in anything they want  you will usually have to validate the input  use lists when there are many fixed choices (too many for radio buttons to be practical) and you want all choices visible at once  use combo boxes when there are many fixed choices, but you don't want to take up screen space by showing them all at once  use a slider or spinner for a numeric value with fixed range An example UI  Did the designer of this UI choose the right components?  assume there are 30 collections and 3 ways to search (by title, author, relevancy) LIBSYS: Search Choose collection: Phrase: Search by: Adjacent words All T itle Y es No OK Default Cancel UI design - multiple screens  you can use a tabbed pane when there are many screens that the user may want to switch between at any moment  or multiple pages, if it's a web site  use dialog boxes or option panes to present temporary screens or options  users hate popup dialogs; use them very rarely  don't prompt for lots of user input by popping up dialogs • instead, put the choices on the existing window as buttons, etc. "Wizards"  wizard: series of dialog boxes to progress through a task  In the mid-1990s, Microsoft changed most of its Windows apps to use "wizards" for installation and settings.  Why did they do this?  What are the pros and cons of a "wizard" UI? Creating a paper prototype  gather materials  paper, pencils/pens  tape, scissors  highlighters, transparencies  identify the screens in your UI  consider use cases, inputs and outputs to user  think about how to get from one screen to next  this will help choose between tabs, dialogs, etc. Application backgrounds  draw the app background (the parts that matter for the prototyping) on its own, then lay the various subscreens on top Representing a changing UI  layers of UI can be placed on top of background as user clicks various options Interactive widgets widget how to simulate it buttons or check boxes tape tabs and dialog boxes index cards or small papers text fields removable tape combo boxes put the expanded choices on a separate paper / Post-It selections highlighted piece of tape a disabled widget cut out a separate gray version that can be placed on top of the normal one Example paper prot. screen Example paper prototype Prototyping exercise  Let's draw a prototype for a music player (e.g. iTunes).  Assume that the program lets you store, organize, and play songs and music videos.  Draw the main player UI and whatever widgets are required to do a search for a song or video.  After the prototypes are done, we'll try walking through each UI.  Things to think about:  How many clicks are needed? What controls to use?  Could your parents figure it out without guidance? UML diagram types  Activity diagrams  Use case diagrams  Sequence diagrams.  Class diagrams  State diagrams 30 Chapter 5 System modeling Use cases  use case: a written description of the user's interaction with the software product to accomplish a goal  interactions between an actor and the system • 3-9 clearly written steps lead to a "main success scenario" • written from actor's point of view, not the system's  benefits of doing use cases?  helps us discover and document functional requirements  agreement as to the system's responsibilities  provides executives a skeleton for planning project priorities  helps provide a list of error cases to test Use cases vs. internal features consider the software to run a mobile phone: Use Cases • call someone • receive a call • send a message • memorize a number Point of view: user Internal Functions • transmit / receive data • energy (battery) • user I/O (display, keys, ...) • phone-book mgmt. Point of view: developer / designer Use cases and requirements  Which of these requirements would probably be represented or mentioned directly in a use case?  Special deals may not run longer than 6 months.  Customers only become preferred after 1 year.  A customer has one and only one sales contact.  Database response time is less than 2 seconds.  Web site uptime requirement is 99.8%.  Number of simultaneous users will be 200 max.  Answer: None!  Most of these are non-functional requirements, so the use cases wouldn't mention them. The user doesn't see them directly. Actors, stakeholders, goals  What are actors and stakeholders in a use case?  actor: anything with behavior (that "acts" on the system)  primary actor: initiates interaction to achieve goal  supporting actor: performs sub-goals in use case  stakeholder: anyone interested in the system  supplier, stock agency, vendor  stakeholder might not "act" in any scenario  goal: action that actor wants to accomplish  summary (multi-sitting), user (one sitting), subfunction (partial) Styles of use cases 1. Actor / goal list (or UML use case summary diagram)  shows all use cases in system 2. Informal use case 3. Formal use case Let's examine each of these in detail... 1. Actor / goal list  Often shown as a list or table of actors and their goals, or a diagram of actors connected to use cases: ACTOR USE CASES INITIATED Club Member Submit Promotion Order Submit Regular Order Potential Member Submit New Subscription Past Member Submit Subscription Renewal Membership Dept. Request Membership Marketing Dept. Create Monthly Promotion Create Seasonal Promotion Create Subscription Program Request Promotion Reports Request Sales Reports Services System Send Subscription Offer Send Club Promotion Send Subscription Renewal Use case exercise  Consider a Netflix-like video rental web system.  A customer with an account can use their membership and credit card in the web app to order a video for rental.  The software can look up movies and actors by keywords.  A customer can check out up to 3 movies, for 5 days each.  Late fees can be paid at the time of return or at next checkout.  Exercise:  Come up with 3-4 use case names for this software.  Identify some of the actors and stakeholders in this system. Informal use case  informal use case: a paragraph describing the scenario  Example (for a Netflix-style video rental system):  Customer Loses a Disc The customer reports to the system that he has lost a disc. The clerk displays the customer's rental record and alerts the customer that this will incur a fee. The customer is asked to confirm the decision. After confirming the decision, the database will be updated to reflect the lost disc, and the customer's record is updated as well to remove the disc and add the fee. The inventory manager is notified of the event and may authorize purchase of a replacement disc. Extensions  What is an "extension"? Why are they useful?  extension: A possible branch in a use case scenario, often triggered by an error or failure in the process.  Useful for finding edge cases that need to be handled and tested.  Do: Think about how every step of the use case could fail.  Do: Give a plausible response to each extension from the system. • Response should either jump to another step of the case, or end it.  Don't: List things outside the use case ("User's power goes out").  Don't: Make unreasonable assumptions ("DB will never fail").  Don't: List a remedy that your system can't actually implement. Example formal use case Use Case 12. Buy stocks over the web Primary Actor: Purchaser (user) Level: user goal Precondition: User already has PAF open and is logged in. Minimal Guarantee: sufficient log information exists that PAF can detect what went wrong. Success Guarantees: remote web site acknowledged purchase, user's portfolio updated. Main success scenario: 1. User selects to buy stocks over the web. 2. PAF gets name of web site to use (E*Trade, Schwabb, etc.) 3. PAF opens web connection to the site, retaining control. 4. User browses and buys stock from the web site. 5. PAF intercepts responses from the web site, and updates the user's portfolio. 6. PAF shows the user the new portfolio standing. Extensions: 2a. User wants a web site PAF does not support: 2a1. System gets new suggestion from user, with option to cancel use case. Cockburn's 4 use case steps 1. Identify actors and goals  What computers, subsystems, people will drive our system?  What does each actor need our system to do? 2. Write the main success scenario  easiest to read; everything else is a complication on this  capture each actor's intent and responsibility 3. List the failure extensions  usually almost every step can fail (bad credit, out of stock...)  note failure condition separately, after main success scenario 4. Describe failure-handling  recoverable: back to main course (low stock + reduce quantity)  non-recoverable: fails (out of stock, or not a valued customer) Use case exercise  Recall our Netflix-like video rental web system example.  A customer with an account can use their membership and credit card in the web app to order a video for rental.  The software can look up movies and actors by keywords.  A customer can check out up to 3 movies, for 5 days each.  Late fees can be paid at the time of return or at next checkout.  Exercise:  Write a formal use case for Customer Orders a Movie. How do we design classes?  class identification from project spec / requirements  nouns are potential classes, objects, fields  verbs are potential methods or responsibilities of a class  CRC card exercises  write down classes' names on index cards  next to each class, list the following: • responsibilities: problems to be solved; short verb phrases • collaborators: other classes that are sent messages by this class (asymmetric)  UML  class diagrams (today)  sequence diagrams  ... Diagram of one class  class name in top of box  write > on top of interfaces' names  use italics for an abstract class name  attributes  should include all fields of the object  also includes derived "properties"  operations / methods  may omit trivial (get/set) methods • but don't omit any methods from an interface!  should not include inherited methods Class attributes  attributes (fields, instance variables)  visibility name : type [count ] = defaultValue  visibility: + public # protected - private ~ package (default) / derived  underline static attributes  derived attribute: not stored, but can be computed from other attribute values  attribute example: - balance : double = 0.00 Class operations / methods  operations / methods  visibility name (parameters ) : returnType  underline static methods  parameter types listed as (name: type)  omit returnType on constructors and when return is void  method example: + distance(p1: Point, p2: Point): double Inheritance relationships  hierarchies drawn top-down with arrows pointing upward to parent  line/arrow styles differ based on parent: • class : solid, black arrow • abstract class : solid, white arrow • interface : dashed, white arrow  we often don't draw trivial / obvious relationships, such as drawing the class Object as a parent Associational relationships 1. multiplicity (how many are used) • *  0, 1, or more • 1  1 exactly • 2..4  between 2 and 4, inclusive • 3..*  3 or more 2. name (what relationship the objects have) 3. navigability (direction) Multiplicity  one-to-one  each student must have exactly one ID card  one-to-many  a RectangleList can contain 0, 1, 2, ... rectangles Association types  aggregation: "is part of"  clear white diamond  composition: "is entirely made of"  stronger version of aggregation  the parts live and die with the whole  black diamond  dependency: "uses temporarily"  dotted line or arrow  often is an implementation detail, not an intrinsic part of that object's state 1 1 aggregation Car Engine Lottery Ticket Random dependency Page Book composition * 1 Class design exercise  Consider this Texas Hold 'em poker game system:  2 to 8 human or computer players  Each player has a name and stack of chips  Computer players have a difficulty setting: easy, medium, hard  Summary of each hand: • Dealer collects ante from appropriate players, shuffles the deck, and deals each player a hand of 2 cards from the deck. • A betting round occurs, followed by dealing 3 shared cards from the deck. • As shared cards are dealt, more betting rounds occur, where each player can fold, check, or raise. • At the end of a round, if more than one player is remaining, players' hands are compared, and the best hand wins the pot of all chips bet.  What classes are in this system? What are their responsibilities? Which classes collaborate?  Draw a class diagram for this system. Include relationships between classes (generalization and associational). Class diag. pros/cons  Class diagrams are great for:  discovering related data and attributes  getting a quick picture of the important entities in a system  seeing whether you have too few/many classes  seeing whether the relationships between objects are too complex, too many in number, simple enough, etc.  spotting dependencies between one class/object and another  Not so great for:  discovering algorithmic (not data-driven) behavior  finding the flow of steps for objects to solve a given problem  understanding the app's overall control flow (event-driven? web- based? sequential? etc.) Qualities of modular software  decomposable  can be broken down into pieces  composable  pieces are useful and can be combined  understandable  one piece can be examined in isolation  has continuity  reqs. change affects few modules  protected / safe  an error affects few other modules Heuristics 2 quick reference  Heuristic 2.1: All data should be hidden within its class.  Heuristic 2.2: Users of a class must be dependent on its public interface, but a class should not be dependent on its users.  Heuristic 2.3: Minimize the number of messages in the protocol of a class.  Heuristic 2.4: Implement a minimal public interface that all classes understand.  Heuristic 2.5: Do not put implementation details such as common-code private functions into the public interface of a class.  Heuristic 2.6: Do not clutter the public interface of a class with items that users of that class are not able to use or are not interested in using.  Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes, that is, a class should only use operations in the public interface of another class or have nothing to do with that class.  Heuristic 2.8: A class should capture one and only one key abstraction.  Heuristic 2.9: Keep related data and behavior in one place.  Heuristic 2.10: Spin off non-related behavior into another class (i.e., non- communicating behavior).  Heuristic 2.11: Be sure the abstractions that you model are classes and not simply the roles objects play. Interface/implementation  public interface: visible data/behavior of an object  can be seen and executed externally  private implementation: internal data/methods in an object  helps implement the public interface; cannot be directly accessed  client: code that uses your class/subsystem  Example: radio • public interface is the speaker, volume buttons, station dial • private implementation is the guts of the radio; the transistors, capacitors, frequencies, etc. that user should not see Poker design question 1  Poker Deck class stores a list of cards; the game needs to be able to shuffle and draw the top card.  We give the Deck class the following methods: add(Card), add(index, Card), getCard(int), indexOf(Card), remove(index), shuffle(), drawTopCard(), etc.  What's wrong with this design?  Heuristic 2.3: Minimize the # of messages in the protocol of a class.  Heuristic 2.5: Do not put implementation details such as common- code private functions into the public interface of a class.  Heuristic 2.6: Do not clutter the public interface of a class with items that users of that class are not able to use or are not interested in using. Minimizing public interface  Make a method private unless it needs to be public.  Supply getters (not setters) for fields if you can get away with it. • example: Card object with rank and suit (get-only)  In a class that stores a data structure, don't replicate that structure's entire API; only expose the parts clients need. • example: If PokerGame has an inner set of Players, supply just an iterator or a getPlayerByName(String) method  Use a Java interface with only the needed methods, and then refer to your class by the interface type in client code. Poker design question 2  Proposed fields in various poker classes:  A Hand stores 2 cards and the Player whose hand it is.  A Player stores his/her Hand, last bet, a reference to the other Players in the game, and a Deck reference to draw cards.  The PokerGame stores an array of all Players, the Deck, and an array of all players' last bets.  What's wrong with this design? Cohesion and coupling  cohesion: how complete and related things are in a class (a good thing)  coupling: when classes connect to / depend on each other (too much can be a bad thing)  Heuristic 2.7: Classes should only exhibit nil or export coupling with other classes; that is, a class should only use operations in the public interface of another class or have nothing to do with that class. • (in other words, minimize unnecessary coupling) Reducing coupling  combine 2 classes if they don't represent a whole abstraction • example: Bet and PlayRound  make a coupled class an inner class • example: list and list iterator; binary tree and tree node • example: GUI window frame and event listeners  provide simpler communication between subsystems • example: provide methods (newGame, reset, ...) in PokerGame so that clients do not need to manually refresh the players, bets, etc. Heuristics 3 quick reference  Heuristic 3.1: Distribute system intelligence horizontally as uniformly as possible, that is, the top-level classes in a design should share the work uniformly.  Heuristic 3.2: Do not create god classes/objects in your system. Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem.  Heuristic 3.3: Beware of classes that have many accessor methods defined in their public interface.  Heuristic 3.4: Beware of classes that have too much noncommunicating behavior.  Heuristic 3.5: In applications that consist of an object-oriented model interacting with a user interface, the model should never be dependent on the interface.  Heuristic 3.6: Model the real world whenever possible.  Heuristic 3.7: Eliminate irrelevant classes from your design.  Heuristic 3.8: Eliminate classes that are outside the system.  Heuristic 3.9: Do not turn an operation into a class. Be suspicious of any class whose name is a verb or is derived from a verb, especially those that have only one piece of meaningful behavior (don't count set, get, print).  Heuristic 3.10: Agent classes are often placed in the analysis model of an application. During design time, many agents are found to be irrelevant and should be removed. Poker design question 3  Our PokerGame class:  stores all the players  stores an array of cards representing the card deck  stores all bets and money  does the logic for each betting round  performs the AI for each computer player's moves  What's wrong with this design? PokerGame God classes  god class: a class that hoards too much of the data or functionality of a system.  Heuristic 2.8: A class should capture one and only one key abstraction.  Heuristic 3.2: Do not create god classes/objects in your system. Be very suspicious of a class whose name contains Driver, Manager, System, or Subsystem.  Heuristic 3.4: Beware of classes that have too much non- communicating behavior, that is, methods that operate on a proper subset of the data members of a class. God classes often exhibit much non-communicating behavior. Poker design question 4  Each new game round, the PokerGame wants to deal cards to each player. During the game, players draw additional cards.  We will create a Dealer class that the PokerGame asks to deal the cards to every player.  Player objects will store a reference to the Dealer. During the game, they will talk to the dealer to draw their cards. The Dealer will notify the Game once all players have drawn.  What's wrong with this design? Poker design question 5  Cards belong to one of four suits. So we have created classes Club, Diamond, Heart, Spade class to represent each suit.  In each game round, one player is the dealer and one is the first better. Also each turn there is a next better waiting. So we have created classes Dealer, NextBetter, FirstBetter.  Every game has several betting rounds, each round consisting of several bets. So we have created classes Bet and CurrentBettingRound.  What's wrong with this design? Proliferation of classes  proliferation of classes: too many classes that are too small in size/scope; makes the system hard to use, debug, maintain  Heuristic 2.11: Be sure the abstractions that you model are classes and not simply the roles objects play.  Heuristic 3.7: Eliminate irrelevant classes from your design. • often have only data and get/set methods; or only methods, no real data  Heuristic 3.8: Eliminate classes that are outside the system. • don't model a Blender just because your company sells blenders; don't necessarily model a User just because the system is used by somebody Poker design question 6  A player may bet only as much $ as they have; and if a prior player has made a "call", the current player cannot raise.  Where should these policies be enforced?  Design 1: Player class remembers whether that player is in the game, what that player's current bet is, whether it is his turn, etc. • Player checks whether a "call" has been made. • Player checks whether he/she has enough to make a given bet.  Design 2: • PokerGame class remembers who is in the game. • Betting class remembers every player's current bets, checks $. • Dealer class remembers whose turn it is. Related data and behavior  Heuristic 2.9: Keep related data and behavior in one place. • avoids having to change two places when one change is needed  Heuristic 3.3: Beware of classes that have many accessor methods ... [This] implies that related data and behavior are not being kept in one place. • "policy" behavior should be where that policy is enforced/enacted UML sequence diagrams  sequence diagram: an "interaction diagram" that models a single scenario executing in the system  perhaps 2nd most used UML diagram (behind class diagram)  relation of UML diagrams to other exercises:  CRC cards  class diagram  use cases  sequence diagrams Parts of a seq.diagram Sequence diag. key parts  participant: object or entity that acts in the diagram  diagram starts with an unattached "found message" arrow  message: communication between participant objects  the axes in a sequence diagram:  horizontal: which object/participant is acting  vertical: time (down = forward in time) Seq. diag. examples Representing objects  Squares with object type, optionally preceded by "name :"  write object's name if it clarifies the diagram  object's "life line" represented by dashed vert. line  messages (method calls) indicated by arrow to other object  write message name and arguments above arrow Messages between objects Messages, continued  messages (method calls) indicated by arrow to other object  dashed arrow back indicates return  different arrowheads for normal / concurrent (asynchronous) calls Lifetime of objects  creation: arrow with 'new' written above it  notice that an object created after the start of the scenario appears lower than the others  deletion: an X at bottom of object's lifeline  Java doesn't explicitly delete objects; they fall out of scope and are garbage-collected Indicating method calls  activation: thick box over object's life line; drawn when object's method is on the stack  either that object is running its code, or it is on the stack waiting for another object's method to finish  nest activations to indicate recursion Activation Nesting Selection and loops  frame: box around part of diagram to indicate if or loop  if -> (opt) [condition]  if/else -> (alt) [condition], separated by horizontal dashed line  loop -> (loop) [condition or items to loop over] Linking sequence diagrams  If one diagram is too large or refers to another, indicate with:  an unfinished arrow and comment,  or a "ref" frame that names the other diagram • when would this occur in our system? Example sequence diagram Forms of system control  What can you say about the control flow of each system?  Is it centralized?  Is it distributed? Flawed sequence diagram 1  What's wrong with this sequence diagram? (Look at the UML syntax and the viability of the scenario.) Flawed sequence diagram 2  What's wrong with this sequence diagram? Why not just code it?  Sequence diagrams can be somewhat close to the code level.  So why not just code up that algorithm rather than drawing it as a sequence diagram?  a good sequence diagram is still a bit above the level of the real code (not all code is drawn on diagram)  sequence diagrams are language-agnostic (can be implemented in many different languages  non-coders can do sequence diagrams  easier to do sequence diagrams as a team  can see many objects/classes at a time on same page (visual bandwidth) Sequence diagram exercise  Let's do a sequence diagram for the following poker casual use case, Start New Game Round : The scenario begins when the player chooses to start a new round in the UI. The UI asks whether any new players want to join the round; if so, the new players are added using the UI. All players' hands are emptied into the deck, which is then shuffled. The player left of the dealer supplies an ante bet of the proper amount. Next each player is dealt a hand of two cards from the deck in a round-robin fashion; one card to each player, then the second card. If the player left of the dealer doesn't have enough money to ante, he/she is removed from the game, and the next player supplies the ante. If that player also cannot afford the ante, this cycle continues until such a player is found or all players are removed. Poker sequence diagram Sequence diagram question  Consider the possible poker use case, Betting Round : The scenario begins after the Start New Round case has completed. The UI asks the first player for a bet. That player chooses to either bet a given amount, or check (no bet). The next player is asked what to do. If the prior player placed a bet, the next player must either match ("see") it, or match it plus add an additional bet ("raise"), or choose not to match and exit the round ("fold"). This continues around the table until an entire pass is made in which all players have either matched all other players' bets or folded. If the next player doesn't have enough money to match the current bet, the player is allowed to bet all of their money. But they can then win only up to the amount they bet; the rest is a "side pot" among the more wealthy players remaining in the round.  Why is it hard to diagram this case as a sequence diagram? Poker sequence diagram 2 Sequence diagram exercise  Let's do a sequence diagram for the following casual use case for a scheduler app, Add Calendar Appointment : The scenario begins when the user chooses to add a new appointment in the UI. The UI notices which part of the calendar is active and pops up an Add Appointment window for that date and time. The user enters information about the appointment's name, location, start and end times. The UI will prevent the user from entering an appointment that has invalid information, such as an empty name or negative duration. The calendar records the new appointment in the user's list of appointments. Any reminder selected by the user is added to the list of reminders. If the user already has an appointment at that time, the user is shown a message and asked to choose an available time or replace the appointment. If the user enters an appointment with the same name and duration as an existing meeting, the calendar asks the user whether he/she intended to join that meeting instead. If so, the user is added to that meeting's list of participants. UML state diagrams  state diagram: Depicts data and behavior of a single object throughout its lifetime.  set of states (including an initial start state)  transitions between states  entire diagram is drawn from that object's perspective  similar to finite state machines (DFA, NFA, PDA, etc.)  What objects are best used with state diagrams?  large, complex objects with a long lifespan  domain ("model") objects  not useful to do state diagrams for every class in the system! State diagram example States  state: conceptual description of the data in the object  represented by object's field values  entire diagram is drawn from the central object's perspective  only include states / concepts that this object can see and influence  don't include every possible value for the fields; only ones that are conceptually different Transitions  transition: movement from one state to another  signature [guard] / activity  signature: event that triggers (potential) state change  guard: boolean condition that must be true  activity: any behavior executed during transition (optional)  transitions must be mutually exclusive (deterministic)  must be clear what transition to take for an event  most transitions are instantaneous, except "do" activities Internal activities  internal activity: actions that the central object takes on itself  sometimes drawn as self-transitions (events that stay in same state)  entry/exit activities  reasons to start/stop being in that state State diagram example U se r a cc o u n t m a n a g e m e n t Super/substates  When one state is complex, you can include substates in it.  drawn as nested rounded rectangles within the larger state  Caution: Don't over-use this feature.  easy to confuse separate states for sub-states within one state State diagram example A T M s o ft w a re s ta te s a t a b a n k State diagram example Ja va t h re a d s ta te s Implementing states  What are some ways to write code to match a state diagram?  state tables (pseudo-code)  nested if/else  switch statements  state enums  State design pattern  state pattern: An object whose sole purpose is to represent the current "state" or configuration of another larger object.  A behavioral pattern.  Often implemented with an enum type for the states.  Each object represents one specific state for the larger object.  The larger object sets its state in response to various mutations.  Allows various observers and interested parties to quickly and accurately know what is going on with the larger object's status.  Analogous to the notion of finite state machines.  Set of states (nodes)  Set of edges (mutations that cause state changes) State pattern State enum example /** Represents states for a poker game. */ public enum GameState { NOT_STARTED, IN_PROGRESS, WAITING_FOR_BETS, DEALING, GAME_OVER; } /** Poker game model class. */ public class PokerGame { private GameState state; public GameState getState() { return state; } public void ante(int amount) { ... state = WAITING_FOR_BETS; // change state setChanged(); notifyObservers(state); } }

Các file đính kèm theo tài liệu này:

  • pdfnguyen_thi_cam_huongch4_5_prototyping_and_system_modeling_sv_078.pdf
Tài liệu liên quan