Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 55 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
55
Dung lượng
712,3 KB
Nội dung
■■ All calls to DAOs are made only through the appropriate business object. For example, to access the BorrowerDao, you call the Borrower business object. ■■ JSP only access the model (in the MVC architectural pattern) via a Value Object. JSPs do not access any business-related objects directly. ■■ JSP contain only presentation-related code. No business functionality is contained in the JSP. ■■ JSPs do not contain any Java scriptlet code. Instead, they use taglibs to conditionally show or hide certain presentation-related data. ■■ Action classes supported by Struts framework contain only code related to extracting the data from the request objects, passing data to the appropriate business object, and returning to the appropriate JSP. There is no business code in these action classes. This enables you to support more than one type of client (other than a Web browser). ■■ Since FormBeans are an implementation mechanism of the Struts framework, we chose to link the FormBeans to the Value Object and then act upon the Value Object elsewhere in the application. This way if you need to use a different framework, you can do so with minimal impact. Performing Detailed Design The purpose of the detailed design is to employ the strategic architectural design and all of its associated implicit guidance (like key patterns for fre- quently performed or critical functionality) and adhere to it while evolving the results of analysis, or even earlier iterations, into a precise and semantically rich representation of what you want to build in code. This gets pretty detailed, including such things as refining individual class specs to ensure that they are complete, meeting the policies of the project for exception propaga- tion, reporting, general handling, and so on. After a few iterations, the design model should be detailed enough so that you can hand the model to a tool, and an appropriate compliable specification so that its classes can be generated with a click of a button. Clearly, the visual parts of UML are insufficient to depict all that is needed; however, the combination of graphical elements and nongraphical UML ele- ments are sufficient to achieve the goal. The following sections describe the nature of detailed design considerations and activities on a key package-by-package basis. As a part of this discussion, we focus on the business and presentation packages described in some of the detailed design decisions based on original analysis. 410 Chapter 11 business Package The business package is primarily composed of control-type classes that rep- resent the coarse-grained logic within the application. All business object classes interact with DAOs from the database package and implement the nec- essary read and write operations. The operations from the analysis have been detailed, which means that some of them have been translated into several operations in the design model and some have changed names. Additionally, as a part of the detailed design, all operations in the design model must have well-defined signatures and return values. NOTE Not even UML 2 diagrams provide a consistent or elegant visual means to depict all the detail you might capture in the detailed design of a single class operation, and you invariably need to specify details of the operation’s signature in its nonvisual specification. Note these changes between the design and the analysis: ■■ The current version of the system does not have to handle checks on whether an item is returned in time, nor does the system have to handle the ordering of reservations. Therefore, the date attribute in the Loan and Reservation classes has not been implemented. ■■ The handling of magazine and book titles is identical (it would be different if a lending period were in our requirements, but it isn’t), so separating the subclasses for Magazine and Book Title is deemed as unnecessary during the analysis. Only a type attribute in the Title class specifies whether the title refers to a book or magazine. There’s nothing in object-oriented design that says the design can’t simplify the analysis! Both of these simplifications can be removed easily if deemed unnecessary in future versions of the application. presentation Package The presentation package is “on top” of the other packages. It presents the ser- vices and information in the system to a user. As noted, this package contains JSP. It is a good idea to limit the amount of Java code contained within your JSP. Also, since you plan to support multiple Web browser platforms, you per- form the validation code on the server, thus reducing the amount of client-side code (that is, JavaScript). Case Study 411 Use-Case Design Having analyzed the use case, and then made various architectural decisions, we need to delve into more detail by further elaborating on the use case using dynamic diagrams. The sequence diagram created during use-case analysis was of a reasonable size, but as more detail is added in design, it becomes unwieldy. Furthermore, as we have created other analysis-level sequence diagrams, we have found significant overlap in behavior. For example, both the Checkout Item use case and the Manage Items use case have requirements regarding searching for a title. Based on these issues, we created an Interaction Overview diagram to partition the diagram into manageable, reusable chunks. Figure 11.13 shows the Interaction Overview diagram for Checkout Item; although it is very sim- ple with no particularly interesting control flow, it greatly improves the under- standability of the model as we delve into more detail. Figure 11.13 Interaction overview diagram for Checkout Item. sd CheckoutItemOverview ref SearchForTitle ref CheckoutItemDetail ref SelectItem 412 Chapter 11 Each of the interaction occurrences in the interaction overview will be designed in its own sequence diagram. It is important to remember that these are not disparate visual diagrams; as we work on each of the detailed sequence diagrams, we are updating the overall model. As new operations are identified while building these dynamic diagrams, they are added to static diagrams and the underlying model. As we walk through these detailed scenarios, we make numerous design decisions, break apart and combine classes, identify rela- tions, and so on. Keeping the model in synch across all the diagrams becomes challenging, but tool support helps. Figure 11.14 shows the detailed sequence diagram for the Checkout- ItemDetail fragment. The figure is worthy of significant explanation both in the area of UML usage and in the actual design being rendered. This interaction starts with the Borrower actor sending a checkout message to a CheckoutJSP object. While messages typically represent an operation or signal, we have chosen to start this interaction with a checkout message that is not attached with an actual operation. Although in a strict technological sense it would be most accurate to show the actor submitting an HTTP POST, that would not best communicate what is happening. So the interaction is shown as being initiated via a “checkout” message. Since this is not associated with an actual operation within the design, the parentheses have been excluded from this message signature. We added a note to remark on the store operation initiated on the Check- outItemAction object. In our use of the Struts framework there is a lot that goes on in constructing the object and getting the method invoked. But we are not authoring that design here, we are just working within it. Rather than show all those details, we are just showing the message as going straight from CheckoutJSP to CheckoutItemAction with the explanation that there are details not shown here. It would rarely be appropriate to create a sequence diagram that shows every small step involved in a complicated interaction. The designer must decide what to include and what to exclude from a diagram. Here, we are excluding the steps involved in getting the borrower identifier and the item identifier from the request object in the CheckoutItemAction class. (Any coder familiar with the HttpServletRequest object will be familiar with how to do this, and it is not worth the space it would take up on this diagram.) We didn’t worry about when objects are created during use-case analysis. In any design, and especially in a Web-based design, you need to make sure that you know when each object is created and who creates it. Here, you can see the ItemMgr created by the initiation of a static getInstance method on the class. The constructors of the other objects are also shown with the exception of DaoFactory. The getItemDao operation is also a static method. Case Study 413 Figure 11.14 CheckoutitemDetail sequence diagram. The DaoFactory is a notable part of this design. As described earlier when discussing the architectural design, we have an ItemDao interface and different classes implementing it for each database we use. Here we are show- ing that the ItemMgr asks the factory for an ItemDao, the factory figures out : Borrower : CheckoutJSP :CheckoutItemAction : ItemMgr : ItemVo Borrower : UserVo : DaoFactory : ItemDao MySql checkout store(mapping : ActionMapping, form : ActionForm, request : HttpSer vletRequest, response : HttpSer vletResponse) Actually goes through some struts machinations to get here getInstance( ) ItemVo( ) setId(id : String) UserVo( ) getBorrower( ) setId(id : String) getDbType( ) sd CheckoutItemDetail ItemDaoMySql( ) checkOutItem(borrowerId : String , itemId : String) setCheckedOut(checkedOut : Strin g) getItemDao( ) : ItemDao checkOutItem(borrowerId : String, itemId : String) setCheckedOut(checkedOut : String) getItemDao( ) : ItemDao store(myItem : Object) 414 Chapter 11 what kind of database we are using, and the ItemDaoMySql is created and returned. The ItemMgr is sending a message directly to the ItemDaoMySql object, but actually has no idea what concrete object is implementing the ItemDao interface. Designing the User Interface A special activity carried out while designing is the creation of the user inter- face—the “look and feel.” Initiated during analysis, you perform this sepa- rately but in parallel to the other design work. (Creating a successful user interface is beyond the scope of this book; consult other sources devoted to this topic for more information.) JSPs are used to display the information and capture the data entered by the user; in short, they act as an interface to the user. Because of the support for multiple Web browser platforms, we made a design decision to put as little Java code as possible within the JSP. Regardless, the decision should always ensure that the requirements for the application are met. In this case, we chose to use the taglibs provided by Struts so that the Java code is not included directly in the JSP. Ultimately, this choice allows for a more readable JSP for purposes of this case study, because certain implementation details are not performed in the JSP. The resulting Unified Library application user interface is composed of a main page (Main.jsp), featuring a menu and an appropriate graphic, from which all other pages in the application can be reached. The other pages typi- cally present a service of the application and are mapped to a particular use case. In some cases, a single user interface, or page, might map to multiple use cases. You might recall from Chapter 3 how the actors interact with use cases, just as in analysis the borrower interacts with a boundary class in the sequence diagram. In design, the borrower boundary class from analysis becomes a JSP. Implementation The implementation activities constitute the actual programming of the classes. One of the reasons to use Java to implement a system is because it works with multiple processors and operating systems. When you use Java, you find a natural progression from the logical classes that were created in the design to the code components during implementation because there is a one- to-one mapping of a class to a Java code file (and a one-to-one mapping to a Java executable .class file). Java also specifies that the name of the file be the same as that of the class it contains. Case Study 415 A component diagram helps in visualizing the physical representation as mapped from the design model. The design was set up to manage the depen- dencies on particular database products. For each entity there is a manager class that depends on a specific DAO interface. Then, the interface is realized by separate classes supporting each of the databases, but the manager does not really depend upon those classes. Instead, they all depend upon the interface. Figure 11.15 shows a class diagram and the corresponding component dia- gram, which shows the artifacts that manifest those classes. Although the dependencies of the physical code files can be surmised by an educated viewer of the class diagram, the component diagram shows them explicitly. Figure 11.15 A class diagram and corresponding component diagram showing the dependencies among a number of title classes. For coding, the specifications are collected from the following diagrams in the design model: ■■ Class diagrams. The class diagrams in which the class is present, show- ing its static structure and relationship to other classes. ■■ State machine diagram. A state machine diagram for the class, showing the possible states and the transitions that need to be handled (along with the operations that trigger the transitions). ■■ Dynamic diagrams (sequence, communication, and activity) in which objects of the class are involved. Diagrams showing the implementa- tion of a specific method in the class or how other objects are using objects of the class. ■■ Use-case diagrams and specifications. Diagrams that show the result of the system give the developer more information on how the system is to be used when he or she might be getting lost in details—losing sight of the overall context. During implementation, deficiencies in the design model surface. You might identify a need for new or modified operations, meaning that the developer TitleMgr TitleDao TitleDaoMySql TitleDaoAccess TitleMgr.java «artifact» TitleDao.java «artifact» TitleDaoMySql.java «artifact» TitleDaoAccess.java «artifact» 416 Chapter 11 has to change the design model. This happens in all projects. What’s important is to synchronize the design model and the code so that the model can be used as final documentation of the system. The Java code examples that follow demonstrate traversing the path from the presentation layer to the controller to the business to the data and back through the layers back to the presentation layer. This is a good example because other implemented use cases employ a pattern similar to this exam- ple. The Java code for the entire application is available on the accompanying CD-ROM. When studying the code, read it with the UML models in mind and try to see how the UML constructs have been realized in the code. Consider these points: ■■ The Java package specification is the code equivalent for specifying to which package in the component or logical view the class belongs. ■■ The private fields in Java correspond to the attributes specified in the model, and the Java methods correspond to the operations in the model. This example demonstrates the checkout of an item from the View Items page (ViewItems.jsp). The first code snippet contains the HTML and the Struts taglibs used for the ViewItems.jsp. This JSP enables a user to enter and submit the data. The JSP sends the request data to the server. // ViewItems.jsp <logic:equal name=”item” property=”isCheckedOut” value=”false”> <td><html:link page=”/Checkout.do?subAction=store” name=”item” property=”itemIdAndTitleId”>Checkout</html:link></td> </logic:equal> Once the request is sent to the server, the CheckoutItemAction object processes the request by executing the appropriate business method, provid- ing the necessary data. CheckoutItemAction uses the Struts framework, which employs the front controller design pattern in conjunction with a Struts ActionForm to retrieve data from the request and to send processing on to the next page as necessary. // CheckoutItemAction.java ItemMgr.getInstance().checkOutItem(user.getId(),request.getParameter(Con stants.ITEM_ID)); Case Study 417 ItemMgr is called by CheckoutItemAction and performs the business- related functionality for items. ItemMgr abstracts out any of the HTTP- or Struts-related processing that takes place in CheckoutItemAction. Item- Mgr calls on the DAO Factory to get the DAO interface. The Factory is respon- sible for determining which implementation to use. In this case, it chooses between a MySQL or an Access DAO. // ItemMgr.java if(this.isCheckedOut(itemId)){ DaoFactory.getItemDao().checkout(item); } The ItemDao[Impl] DAO abstracts and encapsulates the data access code, given a populated Value Object, and sends control back to the business object that called it. In this application, the ItemDao[Impl] is either the Item- DaoMySql or the ItemDaoAccess implementation. // ItemDao[Impl].java PreparedStatement pStmt = conn.prepareStatement(CHECKOUT_STMT); pStmt.setString(1, item.getCheckedOut()); pStmt.setString(2, item.getBorrower().getId()); pStmt.setString(3, item.getDueBack()); pStmt.setString(4, item.getItemId()); pStmt.executeUpdate(); conn.commit(); closeDbConnection(pStmt,conn); As discussed earlier, the example code snippets displayed in this section are similar to how the other use cases are coded. The separation of layers helps promote encapsulation so that you can make a change to one of the layers without affecting the others. The use of the DAO Factory with a single inter- face promotes polymorphism so that the clients of the Factory do not need to know the underlined implementation. By using the Struts taglibs, we reduced the need to write Java code within the JSP, which makes the maintenance of the code easier to manage. Test and Deployment While testing requires significant attention and rigor, we are not going to describe any of the testing efforts in UML here. For this example, we used the 418 Chapter 11 original use cases to test the finished application to determine whether the use cases were supported by the application and can be performed as defined in the use-case descriptions. The application was also tested in a more informal way by putting it into the hands of a user. NOTE A larger-scale application requires more formal specifications against which the software is tested and a defect tracking system. The deployment of the system is the actual delivery, including the docu- mentation. In a real-life project, user manuals and marketing descriptions are typically part of the documentation work. A deployment diagram should also be drawn of the physical architecture, as shown in Figure 11.16. This applica- tion can be used on any computer with the supported Web browser platforms. This diagram shows our simple deployment structure for this case study. The war file simply needs to be put in a J2EE application server on a machine to which clients can connect. Figure 11.16 A deployment diagram for the library system. : AppServer «execution environment» UMLToolkit.war «artifact» LibraryDB : DBMachine Any Client : MidRangeMachine Case Study 419 [...]... Exception Type Interruptible Activity Region Action Interrupted Action2 Interrupted Time Trigger Handle Exception Type 427 Appendix A Parameter Set Set One Action Path One Set Two Action Path Two Exception on an Edge Activity Producing Exception Classifier1 Classifier2 Region1 Activity Partitions: Action1 Action3 Region2 428 Action2 Action4 Visual Glossary Object Node: Object Name Object Node with Signal... Action: Send Signal Accept Signal Action: Accept Signal Fork Node: Join Node 4 29 430 Appendix A Class Diagram Class: ClassName attribute1: type [multiplicity] = default /derivedAttribute: type [multiplicity] attribute2: type = default {property string} classScopedStaticAttribute: type = default operation1(param1, param2) operation2(param1): {property-string} operation3(param3: type = default) Association:... Active Class Active Class Design Element 435 436 Appendix A Powertype PowerTypeClass1 PowerTypeClass2 attribute1: type = default attribute3: type = default Parent Class operation1(param1, param2) operation2(param1) {incomplete, overlapping} :PowerTypeClass1 Child Class A {incomplete, disjoint} :PowerTypeClass2 Child Class B Child Class C Port Provided Interface Classifier Port Name [Multiplicity] Required... {constraint on a comment} ClassName {property = value} attribute2: type = default {constraint} operation1(param1, param2) operation3(param3: type = default) 443 444 Appendix A Extension of a Metaclass «metaclass» Element from Metamodel «stereotype» New Stereotype Element newAttribute: type = default Application of a Profile «Metamodel» UML «import» «Profile» Profile to Use «apply»... «artifact» Order.jar Composite Structure Diagram: Composite Structure Classifier Name Part1: Class1 1 10 Connector Part2: Class2 Part3: Class3 Visual Glossary Deployment Diagram Node: LibraryDB : DBMachine Communication Path: : MidRange Machine LibraryDB : DBMachine 4 39 440 Appendix A Execution Environment: : MidRangeMachine «execution environment» : AppServer Deployment Specification: «deployment... Alternative Package Content Display Package Member Class 1 Member Class 2 441 4 42 Appendix A Diagram Frame: Diagram Type Name of Specific Diagram Frames can include the following diagram types: Activity Class Component Interaction (abbreviated as SD) Package State Machine (abbreviated as SM) Use Case Package Merge: G F A b : String A a : String op2() B op1() C «merge» «merge» H A D Visual Glossary Package Import:... the application to log either debug or trace messages The type of information actually saved in the log should be configurable from the user interface 421 APPENDIX A Visual Glossary Activity Diagram Action: Action Name Initial Node: Activity Final: 423 424 Appendix A Flow Final: Activity Edge, Control Flow or Object Flow: Decision or Merge Node: Decision Input «decisionInput» Items needed for Decision... Pins Activity Edge Connector C C DataStore «datastore» Persistent Information Conditions on Action «localPrecondition» Preconditions Action with Local Conditions «localPrecondition» Postconditions 425 426 Appendix A Structured Activity «Structured» Action One Action Two Expansion Region Collections Entering Streaming, Parallel (Concurrent) or Iterative Action Collections Exiting Edge Weight on Activity... borrowers (for example, UML* ” returns all titles starting with UML ) Exercise 11: Change the design of the search facility of objects, so that multiple search results are handled (currently only the first match is returned) The number of “hits” should be reported, and the user should be able to choose from among the result records Exercise 12: Add a new utility class for creating a log that can be used... Exercise 9: Add the Book Title and Magazine Title classes to the design and add some new appropriate attributes to each of these classes Make the existing Title class abstract and make sure the new classes can be stored persistently Exercise 10: Change the design of the search facility of objects, so that “wildcard” characters can be used when searching for titles, authors, or borrowers (for example, UML* ” . Exceptions Handle Exception Type Exception Type Visual Glossary 427 Parameter Set Exception on an Edge Activity Partitions: Action1 Action3 Action2 Action4 Classifier1 Classifier2 Region2 Region1 Activity Producing Exception Action. to be put in a J2EE application server on a machine to which clients can connect. Figure 11.16 A deployment diagram for the library system. : AppServer «execution environment» UMLToolkit.war «artifact» LibraryDB :. Two 428 Appendix A Object Node: Object Node with Signal as Type Send Signal Action: Accept Signal Action: Fork Node: Join Node Accept Signal Send Signal name Object Name Visual Glossary 4 29