Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 68 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
68
Dung lượng
2,33 MB
Nội dung
300 Code Organization 1:50 PM 9 March 2006 c07.fm 1.0 can factor out both commands and operations, not just GUI-related commands, so that the domain model remain a foundational layer for domain-specific knowl- edge (Evans 2004). The application model layer will typically contain all the commands offered to users by the application: the Command pattern is used in both Swing and SWT for this. A ‘thin’ variant of the application model would typically contain no state apart from that needed by GUI commands. As we are only discussing desktop application GUIs, we are implicitly assuming that all four layers will be deployed on the client side. This architecture can also be deployed with the upper two layers (the view and application models) on the client and the other two layers on the server. This latter scenario is more common for Web clients, in which there is no need for off-line capabilities and the whole domain model can comfortably operate on the server side. 7.3 A three-layer organization for GUI code It is now possible to look at the details of a specific implementation of the three- layer architecture discussed in the previous section. This section discusses a reuse- based decomposition of a client implementation that is based on three parts: In cases in which a high level of sophistication is needed, the infrastructure layer can also handle the application’s internal communication infrastructure, or other services typical of server-side applications, such as JMS support, advanced caching mechanisms, and the like. Figure 7.5 Four-layer application architecture overview c07.fm Page 300 Thursday, March 9, 2006 1:51 PM A three-layer organization for GUI code 301 1:50 PM 9 March 2006 c07.fm 1.0 presentation, application, and service. These three parts are composed mainly of Java classes, possibly with other resources such as images, support files, and so on. This scheme has its strengths and weaknesses, as we will see. Our objective is to discuss this type of GUI architecture in some detail, rather than suggest that it is some sort of ‘silver bullet’ architecture. Overview The presentation layer is what we see on the screen. Users interacting with dialogs or watching a splash window at application start-up are dealing with presentation objects. The other two layers are the ‘behind-the-scenes’ of the software: • The application layer is where the application domain’s objects are gathered, the business objects or domain logic. • The service layer provides a wide range of standardized utility services. Figure 7.6 illustrates this. There is always a presentation layer in a user interface. It is made up of compo- nents that are usually inherited from javax.swing.JComponent (or, in SWT, from org.eclipse.swt.widgets ), plus other classes that represent user input, or that are responsible for interaction and control. The user interacts with the presenta- tion layer mostly with mouse and keyboard. This layer separates users from the application’s logic. Figure 7.6 Three-layer GUI architecture overview c07.fm Page 301 Thursday, March 9, 2006 1:51 PM 302 Code Organization 1:50 PM 9 March 2006 c07.fm 1.0 The application layer lies immediately behind the presentation layer, tightly coupled to it. It is made up of Java classes that implement the logic and the busi- ness objects that are represented graphically in the presentation layer. If we have a clock window, for example, the application layer will contain a Date object that is tightly coupled with a DateViewer widget in a panel with some buttons, and so on, all of them in the presentation layer. The third layer comes into play when we want to reuse some aspect of the code. Let’s suppose we want to add more features to the clock. We want to offer inter- national language support, with on-line help, and the option of customizing the clock’s appearance depending on a user’s tastes, and in such a way that users customizations are persistent across sessions. Thinking of these services as a sepa- rate layer helps in reusing them more systematically. The following table shows how data is managed by the various layers: Some of the benefits of this layering scheme are: • Division of work. In the early stage of a development cycle, somebody will work on the GUI, designing and validating it with users, while perhaps Table 7.1 Relationship between layers and data Type Data Presentation Depends on the underlying GUI technology Service Authorization Configuration Help Localization Security User Profiles Etc. Application Application-dependent This basic architecture is not intended to be all-encompassing, but rather to impart a minimum organizational infrastructure to GUI code, without being too pervasive. Developers can adapt it to their own production environments and needs. c07.fm Page 302 Thursday, March 9, 2006 1:51 PM A three-layer organization for GUI code 303 1:50 PM 9 March 2006 c07.fm 1.0 someone else will take care of the business objects specific to the application domain, database issues, and so on. The two groups might even work in parallel after an initial period. This architecture helps to divide responsibili- ties neatly and so better organize the work. • Integration with existing toolkits. This approach fits nicely with the Model- View-Controller (MVC) architecture and with similar object-oriented mecha- nisms that are in widespread use in Java programming, even though it can be used with simpler libraries such as SWT or AWT as well. • Flexibility . One of the main practical advantages of such an architecture is its neutrality – it can be used for both medium-sized and small GUIs. • Common reference. Like any kind of structured organization, this architecture is also useful for reference. Throughout the product lifecycle (and in this book as well) we can address functional parts with the same name. This helps developers working in teams to standardize their cooperative efforts. It also gives us an overview of all the challenges and problems designers and developers will face during the product lifecycle. Some of this scheme’s drawbacks are: • It needs a clearly-defined separation between presentation and application. If this is not maintained, the architecture can easily degrade. • Extra care in testing is required. The service layer can be a problem for testing. Mock-ups are needed for expensive services such as remote connections, databases, and so on, and special care is needed with Singletons that initialize statically. • It gives poor insulation for complex domain models. The model doesn’t scale well for projects with a complex domain model. In these cases a four-layer archi- tecture is strongly recommended. The following three sections look more closely at the three individual layers. The presentation layer The structure of the presentation layer is repetitive: the user interacts with some widgets, clicking with the mouse, filling up text fields, and so on. A control manager 11 is normally used to support the widgets, supervising all the widgetry and keeping it coherent – for example, disabling fields in a form until all required data is valid. Figure 7.7 shows a high-level conceptual view of the presentation layer with a centralized control state that implements the Mediator design pattern. 11. See Chapter 6. c07.fm Page 303 Thursday, March 9, 2006 1:51 PM 304 Code Organization 1:50 PM 9 March 2006 c07.fm 1.0 In Swing this layer includes all the views in the MVC, plus related support classes such as table decorators, together with the objects that represent user input and control. In SWT it includes the content widgets. The application layer If we use Swing or other MVC-based frameworks, all the MVC models needed for the views in the presentation layer can be gathered here, as shown in Figure 7.8. As well as these, other objects are needed for the particular domain with which we are working. The application layer is the most variable of the three, because it implements the logic of the application domain (possibly accessing remote services) and also commands that use that logic. The application layer might also include other details apart from a representation of the business domain, such as commands, domain-specific support functions, and so on, and for this reason we prefer to call it the application layer. MVC models can be used as the interface with the application layer. This is a simple choice and helps to decouple the two layers clearly – but ‘pollutes’ the application layer with classes that are needed to extend the GUI toolkit’s inter- faces for data models. The application layer, also known as the ‘business domain model,’ is domain- specific. You can find a comprehensive and insightful discussion of its design in (Evans 2004). Figure 7.7 The presentation layer Even if your GUI does not use the Swing library, or JFace on top of SWT, this architecture still turns out to be useful – as shown in Chapter 10 in the context of J2ME GUIs. c07.fm Page 304 Thursday, March 9, 2006 1:51 PM A three-layer organization for GUI code 305 1:50 PM 9 March 2006 c07.fm 1.0 The service layer The service layer implementation described here has just one class, Service- Manager , as its interface with the other two layers. It usually performs all the initializations – loading configuration files, initializing external devices, and so on – and offers infrastructure services to the application and presentation layers. A common service offered to the presentation layer, for example, is localization support of widget appearance. Figure 7.9 illustrates a possible structure for this layer. Figure 7.8 One flavor of application layer Figure 7.9 The service layer c07.fm Page 305 Thursday, March 9, 2006 1:51 PM 306 Code Organization 1:50 PM 9 March 2006 c07.fm 1.0 Providing a single point of access is useful and intuitive, and can be used in a wide variety of situations, but it may pose problems in non-trivial applications. Code supervision should be enforced to prevent invalid services being moved into this layer, such as specialized Factories, for example. A configuration facility can be used to plug in new services, such as support for special hardware devices. Even in simpler GUIs that have a minimal service layer implementation a service layer could be useful, because it enforces a standard, systematic yet simple struc- ture on the code. 7.4 Two examples of a three-layer implementation Two examples of the three-layer architecture serve to illustrate it: • A simple example describes the architecture from a technical, programmer’s viewpoint. • The second example zooms out to see how the model can be used to organize a more complex and formal project. These examples illustrate the practical application of the architectures described in the previous section, and will be discussed in detail in the following chapters. We know from Chapter 3 that we can think of components – that is, subclasses of the Component class – as being divided into three groups, in order of complexity and development cost: • Standard components, such as Tree , Panel . • Custom components, such as DataBaseTree , MyCoolButton , obtained from the specializations of standard – Sun, Eclipse, or third-party – components. • Ad-hoc components, such as the graphic equalizer in a music player, for example, that have no counterpart in standard components and must be developed from scratch. An MP3 player Kenrick and Rajeev are two friends in their first university year of study in computer science. They are developing some Java classes for playing MP3 files, for fun. One day Kenrick comes to his friend, very excited. He has found out from a Web site that a Java shareware distribution being launched on CD-ROM in a week’s time. They will therefore have only a very short time to ship their product, and although their MP3 decoder classes work nicely, there is no GUI at all at the moment. Rajeev has some experience with the Java Swing library, and decides to develop the GUI with the help of this book, while Kenrick will add the file streaming and other essential features to the Java audio subsystem classes they have already developed. c07.fm Page 306 Thursday, March 9, 2006 1:51 PM Two examples of a three-layer implementation 307 1:50 PM 9 March 2006 c07.fm 1.0 Rajeev is amazed by the possibilities Java can give their GUI, such as portability and a pluggable look and feel, but at present he has no time for advanced GUI features. He decides to build a simple GUI for the first release, leaving ‘cool’ features for future releases. The paper mock-up is straightforward, and the GUI design is inspired by similar products already on the market. Rajeev gets into the implementation details of his GUI, devising the following top- level containers: • A main frame. • Four modal, unrelated dialogs, one for information about the current track, another for application settings, one for the help, and one for choosing files. • Two accessory pop-ups – a pop-up window for the volume control, and a simple pop-up menu triggered by the right mouse-button on the track list. Rajeev decides not to use any particular UI approach, mainly because he has never used one before and feels that he has no time to learn new material at present. He sketches the main window on paper, defining all its components, shown in Table 7.2, together with their development complexity. The next step – to define the required services – is straightforward: Rajeev decides not to use any standard service at all. He then defines the user interaction, basing it on the following commands. • Track-related commands: – Play –Stop –Rewind – Fast forward –Pause – Show track properties, which displays the track properties dialog – Step back, which rewinds the current track by five seconds – Step forward, which steps the current track forward by five seconds Table 7.2 The main frame components for the MP3 player Component name Java class Type ToolBar JtoolBar Standard TrackList Jlist Custom TrackSlider Jslider Standard StatusBar JstatusBar Ad-hoc c07.fm Page 307 Thursday, March 9, 2006 1:51 PM 308 Code Organization 1:50 PM 9 March 2006 c07.fm 1.0 • General commands: – Preferences, which shows the dialog for changing the application’s options – Help, which shows a simple dialog with a text area describing authors and product – Set volume, which shows the pop-up window with the volume slider control • Track-list commands: – Next track –Previous track – Add to track list – Remove from track list – Select from track list, which plays the selected track in the list The other user interactions are the right-click on the track list, which displays a menu with track list-related commands, the double-click that launches the ‘Select from track list’ command, and the keyboard accelerators. A simple director class will manage all the GUI coherence – for example, the track list navigation arrows should be disabled when it is not possible to use them, such as at the beginning or the end of the list. Once finished with the director class, the presentation layer and the service layer (here empty) are defined. The last step is to define the model classes in the appli- cation layer. There are three MVC models: the track list, the current track elapsed time, and the volume slider models. Another application class represents the tracks to be played. Rajeev decides to incorporate the elapsed time model in the track class, because this simplifies the handling of the two views. The same object – the current elapsed time for the track – is observed by two views: the interactive slider and the read- only digital display at the bottom-right of the main frame. This type of model – the slider model and the ad-hoc digit display model within the status bar – is quite simple. The track list model is just an ordered collection of Track object special- izations of the ListModel class. Rajeev adds the other application classes that have been refined by Kenrick meanwhile, resulting in the GUI shown in Figure 7.10. Kenrick simply couldn’t believe it. With his remaining time, Rajeev refines the StatusBar component and tests the GUI with the help of their friends. This example shows how a principled, top-down general implementation organi- zation also helps in the development of small applications, not only at a technical level, but also in team organization. c07.fm Page 308 Thursday, March 9, 2006 1:51 PM Two examples of a three-layer implementation 309 1:50 PM 9 March 2006 c07.fm 1.0 An electronic circuit simulator and editor In the next example we take another perspective, without going into technical details, to see how a three-layer architecture can be used for managing large projects. A joint venture by a university and a private software firm is set up to develop a graphical electronic circuit simulator and editor in Java. The plan is to begin by wrapping an existing, reliable simulation tool that is based on a command-line user interface that has been developed by university researchers over the past ten years. In future releases the code will be ported entirely from C to Java, so that the application will become 100% pure Java and totally cross-platform. The goal for the first release is to lay out the GUI, while the backend will interface with the existing legacy command-line application. Users are both engineers and academics, and the software will be released in two versions: • A basic one as freeware, which will provide the same functions as the existing command-line application. • A ‘professional’ edition that will be the starting point for future enhancements. The software company will hold the copyright for the source code, possibly expanding the software to handle more features in the professional edition. They Figure 7.10 The MP3 player’s GUI (Metal1.2) This highlights an interesting and important aspect of the Java community – not only its end users, but also developers, architects and designers. Java technology is widely used by open source and not-for profit organizations, where the Java characteristics of portability, inexpensiveness, and inherent multi-vendor sourcing, make it the perfect development choice in these cases. c07.fm Page 309 Thursday, March 9, 2006 1:51 PM [...]... desc., im=image), followed by "." and 06: # 3.finally a short description of the string 07: # (in case of simple text label the 2-char code is omitted) 08: # 09: # (c) 2000-20 06 Mauro Marinilli 10: # 11: 12: c6.util.ui.memory.MemoryCheckBox.label=Don't\ show\ this\ message\ again 13: 14: c4.common.LoginDialog.title=Log\ In 15: c4.common.LoginDialog.login=Login\ Name: 16: c4.common.LoginDialog.login.mn=l... of the classic Prototype software design pattern (Gamma et al 1994) This service 16 See Chapter 4 1:50 PM 9 March 20 06 c07.fm 1.0 320 Code Organization can be used by the application for creating new objects from templates, or directly by the user, as in the Library example application in Chapter 15 In this latter case, users can modify the templates themselves using the same GUI that is used to modify... pattern that is interpreted by fixed devices The application also works as an ‘e-wallet’ – the user can purchase transportation credits electronically – and receives broadcast messages about transit and other transport-related news These messages are optional: the user needs to pay their 1 2:4 PM 9 March 20 06 A small Java application that is intended to be executed within a managed container conforming with... useful, but none yet suit the uniqueness of the Java platform We will introduce Java rich clients (RC) gradually, starting from their differences from Web applications, and next from the other GUI client environments First of all, let’s look at the properties that define a rich client for the purposes of this book: • 2:4 PM 9 March 20 06 They offer richer user experience than other media If rich clients... occasional users, or when users access the application from more than one machine, then Web applications are also preferable • When end user productivity and overall experience are important, or when off-line capabilities are needed, rich clients should be preferred over Web applications This latter decision should be based on an assessment of the real need, however, rather than ‘nice-to-have’ features Java. .. needs to be input by users to complete a transaction A requirement states that at any point users can close the screen, and all the data they input previously should reappear when they re-run the application in a new session to complete the transaction A simple way to achieve this is to serialize the screen data state Java Bean locally and resume it as needed 2:4 PM 9 March 20 06 c08.fm 1.0 331 Runtime... environment, it can camouflage itself alongside the other cell phone applications, and so appear more natural to its users The application must be easy to download, for example from a Web page, and be easy to use, because repetitive users are going to use it more than once a day Being written in Java allows it to be deployed inexpensively to a wide range of devices This is an imaginative – and imaginary –... Countless book discuss good OO design, such as (Martin 2002) mentioned above For a more specific discussion, see for example ‘Evolving Java- based APIs’ by Jim des Rivières, available at http://eclipse.org/eclipse/development /java- api-evolution.html 1:50 PM 9 March 20 06 c07.fm 1.0 317 The service layer with properties files, although more elaborate schema are possible, such as XML files Localization... regards the user experience It’s useful to briefly review the reasons why we might need to develop a rich client application: • When the application is targeted at many different platforms, or when ease of deployment and administration is favored over end -user experience, Webbased applications should be preferred over other client strategies In situations in which a computer is used by more than one user, ... Introduction Figure 8.1 shows a screen shot of a fictitious application for Java- powered cell phones This illustrates a type of Midlet1 (see Chapter 10) that is provided by the central transportation authority of a major city to its clients The user is admitted into the transportation system by means of an ingenious system – when requested by the user, the cell phone screen displays a special machine-readable . developed. c07.fm Page 3 06 Thursday, March 9, 20 06 1:51 PM Two examples of a three-layer implementation 307 1:50 PM 9 March 20 06 c07.fm 1.0 Rajeev is amazed by the possibilities Java can give their. to run a Java application. • Java Web Start runtime execution. Given the particular implementation of Java Web Start technology, some mechanisms for loading resources cannot work. • Java programs. for example ‘Evolving Java- based APIs’ by Jim des Rivières, available at http://eclipse.org/eclipse/development /java- api-evolution.html c07.fm Page 3 16 Thursday, March 9, 20 06 1:51 PM The service