Java Enterprise Design Patterns Patterns in Java (Mark Grand) (Z-Library)

Author: Mark Grand

科学

This third volume from Mark Grand features 38 design patterns for developing real-world Java distributed and enterprise applications. Some of the key concepts covered are reliable transaction processing, distributed objects, reliable message passing, concurrency management, object persistence, and coping with time. The popularity of technologies for dealing with these issues waxes and wanes. However, by explaining many of the problems that technologies such as J2EE are designed to solve, this book documents the skills necessary for designing software that will remain useful with both current and future technologies.

📄 File Format: PDF
💾 File Size: 3.1 MB
26
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
TE AM FL Y Team-Fly®
📄 Page 2
Java Enterprise Design Patterns MARK GRAND John Wiley & Sons, Inc. New York ● Chichester ● Weinheim ● Brisbane ● Singapore ● Toronto Java™ Enterprise Patterns in JavaTM, Volume 3 MARK GRAND John Wiley & Sons, Inc. New York ● Chichester ● Weinh im ● Bri ba e ● Singapore ● Toronto
📄 Page 3
Publisher: Robert Ipsen Editor: Theresa Hudson Developmental Editor: Kathryn A. Malm Managing Editor: Angela Smith New Media Editor: Brian Snapp Text Design & Composition: Designations used by companies to distinguish their products are often claimed as trademarks. In all instances where John Wiley & Sons, Inc., is aware of a claim, the product names appear in initial capital or ALL CAPITAL LETTERS. Readers, how- ever, should contact the appropriate companies for more complete information regarding trademarks and registration. This book is printed on acid-free paper. ●∞ Copyright © 2002 by Mark Grand. All rights reserved. Published by John Wiley & Sons, Inc., New York Published simultaneously in Canada. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4744. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 605 Third Avenue, New York, NY 10158-0012, (212) 850-6011, fax (212) 850-6008, E-Mail: PERMREQ @ WILEY.COM. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold with the understanding that the publisher is not engaged in professional services. If professional advice or other expert assistance is required, the services of a competent professional person should be sought. Library of Congress Cataloging-in-Publication Data: Grand, Mark. Java Enterprise design patterns / Mark Grand. p. cm. ISBN 0-471-33315-8 (pbk.: alk. paper) 1. Java (Computer program language) 2. Web servers. 3. Object- oriented programming (Computer science) I. Title. QA76.73.J38 G72 2001 005. 13'3—dc21 2001045611 Printed in the United States of America. 10 9 8 7 6 5 4 3 2 1
📄 Page 4
Acknowledgments vii About the Author viii Chapter 1 Introduction to Software Patterns 1 Description of Patterns 2 Pattern Name 3 Synopsis 3 Context 3 Forces 3 Solution 4 Consequences 4 Implementation 4 Known Uses 4 Code Example 4 Related Patterns 4 A Very Brief History of Patterns 5 Organization of This Book 5 C O N T E N T S
📄 Page 5
Chapter 2 Overview of UML 7 Class Diagram 8 Collaboration Diagram 18 Statechart Diagram 26 Deployment Diagram 28 Chapter 3 The Software Life Cycle 29 Chapter 4 Transaction Patterns 33 Acid Transaction 37 Composite Transaction 55 Two Phase Commit 65 Audit Trail 75 Chapter 5 Distributed Architecture Patterns 81 Shared Object 83 Object Request Broker 89 Object Replication 99 Redundant Independent Objects 109 Prompt Repair 115 Mobile Agent 119 Demilitarized Zone 129 Process Pairs 133 Chapter 6 Distributed Computing Patterns 137 Object Identifier 139 Registry 149 Protection Proxy 157 Publish-Subscribe 175 Retransmission 187 Mailbox 195 Heavyweight/Lightweight 203 Heartbeat 209 Connection Multiplexing 229 Chapter 7 Concurrency Patterns 275 Session Object 277 Lock File 285 Static Locking Order 291 Optimistic Concurrency 297 Thread Pool 303 Ephemeral Cache Item 325 Transaction State Stack 337 iv ■ CONTENTS
📄 Page 6
Chapter 8 Temporal Patterns 347 Time Server 349 Versioned Object 355 Temporal Property 373 Chapter 9 Database Patterns 387 Persistence Layer 389 CRUD 407 Stale Object 413 Type Conversion 423 IsDirty 431 Lazy Retrieval 439 Appendix A Persistence Framework 445 Bibliography 475 Index 477 Contents ■ v
📄 Page 7
(This page has no text content)
📄 Page 8
A C K N O W L E D G M E N T S This book would not have been possible without the inspiration, encour- agement and assistance of others. I want to thank Brad Appleton for his diligent reviews and concern with form. Wolfgang W. Keller provided extensive feedback on the transaction patterns chapter. Frank Sauer provided excellent feedback on the database patterns chapter. I also want to thank the members of the pattern discussion group at University of Illinois, Champaign-Urbana, for their invaluable comments on my manuscript: Joe Yoder, Brian Foote, Hiroaki Nakamura, Roger Whitney, Ralph Johnson, Brian Marick, Wanghong Yuan, Paul Rubel, Frederico Balaguer, Alejandra Garrido, Don Roberts, Zhijiang “John” Han, Weerasak Witthawuskul, Peter Hatch, Dragos Malolescu, and Les Tyrrell. Last, but not least, I would like to thank my wife Nicole for her sup- port and encouragement through the most difficult of times. This book could not have been finished without her understanding and patience.
📄 Page 9
A B O U T T H E A U T H O R Mark Grand is a consultant specializing in distributed systems, object- oriented design, and Java. He is currently working on an open source framework for gluing components and programs into an application. Mark Grand is the author of a series of books titled Patterns in Java. He is a consultant who specializes in Distributed Systems, Object Oriented Design, and Java. He was the architect of the first commercial B2B e-commerce product for the Internet. TE AM FL Y Team-Fly®
📄 Page 10
C H A P T E R Introduction to Software Patterns 1 Software patterns are reusable solutions to recurring problems that occur during software development. For purposes in this book, we refer to soft- ware patterns simply as patterns. What makes a bright, experienced programmer so much more produc- tive than a bright but inexperienced programmer? Experience. Experience gives programmers wisdom. As programmers gain experience, they recog- nize the similarity between new problems and those problems that they have solved before. With even more experience, they recognize that the solutions for similar problems follow recurring patterns. Experienced programmers recognize the situations where these patterns apply and quickly draw on existing solutions without having to stop, analyze the problems, and then pose possible strategies. When a programmer discovers a pattern, it’s just an insight. In most cases, to go from a nonverbalized insight to a well-thought-out idea that the programmer can clearly articulate is surprisingly difficult. It’s also an extremely valuable step. When we understand a pattern well enough to put it into words, we are able to intelligently combine it with other patterns. More important, once put into words, a pattern can be used in discussions among programmers who know the pattern. That allows programmers to more effectively collaborate and combine their wisdom. It can also help to 1
📄 Page 11
avoid the situation where programmers argue over various solutions to a problem only to find out later that they were really thinking of the same solution but expressing it in different ways. Putting a pattern into words has an additional benefit for less experi- enced programmers who have not yet discovered the pattern. Once a pat- tern has been put into words, more experienced programmers can teach it to programmers who are new to the pattern. This book provides experienced programmers with a common vocab- ulary to discuss patterns. It also allows programmers who have not yet dis- covered a pattern to learn about the pattern. Though this book includes a substantial breadth of patterns, addi- tional patterns did not make it into this book. You, dear reader, may dis- cover some of these patterns for yourself. Some patterns you discover may be highly specialized and of interest to only a small number of people. Other patterns may be of very broad interest and worthy of inclusion in a future volume of this book. If you wish to communicate such a pattern to me, my e-mail is mgrand@mindspring.com. The patterns cataloged in this book convey constructive ways of orga- nizing parts of the software development cycle. Other patterns that recur in programs are not constructive. These types of patterns are called AntiPatterns. Because AntiPatterns can cancel out the benefits of patterns, this book does not attempt to catalog them. Description of Patterns Patterns are usually described using a format that includes the following information: • A description of the problem that includes a concrete example and a solution specific to the concrete problem • A summary of the forces that lead to the formulation of a general solution • A general solution • The consequences, good and bad, of using the given solution to solve a problem • A list of related patterns Pattern books differ in how they document patterns. The format used in this book varies depending on which phase of the software life cycle the pattern addresses. The patterns in this book are related to a few different phases of the software life cycle. The pattern descriptions are organized into the section headings described here. Because the nature of the pat- terns varies, not every heading is used in every pattern. 2 ■ CHAPTER ONE
📄 Page 12
Pattern Name The Pattern Name section consists of the name of the pattern and a bibliogra- phy reference that indicates where the pattern originated. Most patterns don’t have any additional text under this heading. For those that do, this section contains information about the derivation or general nature of the pattern. The bibliography reference indicates where the ideas in the pattern were first written in the form of a pattern. Because patterns are based on established practices, in many cases there are other sources of the ideas in the pattern other than the bibliography reference. Usually, the author of a pattern is not the first person to discover the ideas that underlie the pat- tern. In particular, I do not claim to be the first person to discover the ideas presented in this book. Those patterns with a bibliographic reference to this book merely indicate that I know of no other place where that par- ticular set of ideas has been documented as a pattern. The bibliography entry next to a pattern name is provided to help you trace the development of the pattern itself, not the underlying ideas. Synopsis The Synopsis section provides a brief summary of the pattern—both the essence of the problem that the pattern aims to solve and the solution pro- vided by the pattern. The synopsis is primarily directed at experienced pro- grammers who may recognize the pattern as one they already know, but may not have had a name for. After recognizing the pattern from its name and synopsis, it may be sufficient to skim over the rest of the pattern description. Don’t be discouraged if you don’t recognize a pattern from its name and synopsis. Instead, read carefully through the rest of the pattern description to better understand it. Context The Context section describes the problem that the pattern addresses. For most patterns, the problem is introduced in terms of a concrete example. After presenting the problem in the example, the Context section suggests a design solution for that problem. Forces The Forces section summarizes the considerations that lead to the prob- lem’s general solution presented in the Solution section. The Forces sec- tion also summarizes considerations that would lead you to forgo the Introduction to Software Patterns ■ 3
📄 Page 13
solution. The reasons for not using a solution are as important as the rea- sons for using a solution. Both are organized as bulleted points as follows: ⁄ Reasons to use a solution are bulleted with a happy face. Ÿ Reasons not to use a solution are bulleted with a sad face. Solution The Solution section is the core of the pattern. It describes a general- purpose solution to the problem that the pattern addresses. Consequences The Consequences section explains the implications—good, bad, and neu- tral—for using the solution. Most consequences are organized into bul- leted points like this: ⁄ Good consequences are bulleted with a happy face. • Neutral consequences are bulleted with a dot. Ÿ Bad consequences are bulleted with a sad face. Implementation The Implementation section describes the important considerations to be aware of when executing the solution. It may also describe some common variations or simplifications of the solution. Some patterns may not have an Implementation section because these concerns are not relevant. Known Uses The Known Uses section highlights some well-known uses for the pattern. Code Example The Code Example section contains a code example showing a sample implementation for a design that uses the pattern. For some patterns, such as Graphical User Interface (GUI) design patterns, a code example is not relevant. Related Patterns The Related Patterns section contains a list of patterns that are related to the pattern described. 4 ■ CHAPTER ONE
📄 Page 14
A Very Brief History of Patterns The idea of software patterns originally came from the field of architec- ture. An architect named Christopher Alexander wrote some revolutionary books that describe patterns in building architecture and urban planning: • A Pattern Language: Towns, Buildings, Construction (Oxford University Press, 1977) • The Timeless Way of Building (Oxford University Press, 1979) The ideas presented in these books are applicable to a number of fields outside of architecture, including software. In 1987, Ward Cunningham and Kent Beck used some of Alexander’s ideas to develop five patterns for user-interface design. They published a paper on the UI patterns at OOPSLA-87: Using Pattern Languages for Object-Oriented Programs. In the early 1990s, four authors—Erich Gamma, Richard Helm, John Vlissides, and Ralph Johnson—began work on one of the most influential computer books of this decade: Design Patterns. Published in 1994, the book popularized the idea of patterns. Design Patterns is often called the Gang of Four, or GoF, book. This book you are reading represents an evolution of patterns and objects since the GoF book was published. The GoF book used C++ and SmallTalk for its examples. I use Java and take a rather Java-centric view of most things. When the GoF book was written, the Unified Modeling Language (UML) did not exist. It’s now widely accepted as the preferred notation for object-oriented analysis and design. Therefore, that is the notation I use in this book. Organization of This Book This book follows my previous two works on Patterns in Java. The first vol- ume focused exclusively on general-purpose design patterns. The second volume moved away from design patterns to include a variety of patterns used to assign responsibilities to classes, design GUIs, write code, and test software. This third volume contains design and architectural patterns for use in distributed and enterprise applications. The topics include patterns related to transaction design, distributed computing, concurrency, time, and using databases with object-oriented programs. As with my previous books on Java patterns, this one begins with a brief description of the UML subset used to document the patterns. Chapter Introduction to Software Patterns ■ 5
📄 Page 15
3, containing an overview of the software life cycle, provides the context in which the patterns are used. Chapter 3 also offers a case study that includes examples for using the patterns. The remaining chapters describe different types of patterns. The CD-ROM that accompanies this book contains all of the code examples. In some cases, the examples on the CD-ROM are more complete than those that appear in this book. The CD-ROM also contains trial ver- sions of software related to the patterns. The Java examples that appear in this book are based on JDK 1.3. 6 ■ CHAPTER ONE
📄 Page 16
C H A P T E R Overview of UML 7 The Unified Modeling Language (UML) is a notation that you can use for object-oriented analysis and design. This chapter contains a brief introduc- tion to the UML and to the subset and extensions of the UML that are used in this book. For a complete description of the UML, see www.omg.org. Books on UML define the pieces of information stored in instances of a class as attributes; they define a class’s encapsulations of behavior as oper- ations. Those terms, like UML, are not specific to any implementation lan- guage. However, this book is not language neutral. It assumes that you are using Java as your implementation language. This book also uses mostly Java-specific terms rather than terms that are language neutral but less familiar to Java programmers. For example, I use the words attribute and variable interchangeably, preferring the Java-specific term, variable. I use the words operation and method interchangeably, preferring the Java- specific term, method. UML defines a number of different kinds of diagrams. The rest of this chapter is organized into sections that describe each of those diagrams and the elements that appear in them. If you are experienced with object-oriented design, you will find most of the concepts that underlie the UML notation to be familiar. If you find many of the concepts unfamiliar, read only as much of this chapter as you 2
📄 Page 17
feel comfortable with. In later chapters, if a UML diagram contains some- thing you want explained, return to Chapter 2 and find a diagram that con- tains a similar UML element. Class Diagram A class diagram is a diagram that shows classes, interfaces, and their relationships. The most basic element of a class diagram is a class. Figure 2.1 shows many of the features that a class can have within a class diagram. Classes are drawn as rectangles. The rectangles can be divided into two or three compartments. The class rectangle shown in Figure 2.1 has three compartments. The top compartment contains the name of the class. The middle compartment lists the class’s variables. The bottom compart- ment lists the class’s methods. The symbols that precede each variable and method are visibility indi- cators. The possible visibility indicators and their meanings are as follows: + Public # Protected - Private The variables in the middle compartment are shown as follows: visibilityIndicator name : type Therefore, the two variables shown in the class in Figure 2.1 are pri- vate variables. The name of the first variable is instance and its type is AudioClipManager. The name of the second variable is prevClip and its type is AudioClip. 8 ■ CHAPTER TWO AudioClipManager -instance:AudioClipManager -prevClip:Audioclip «constructor» -AudioClipManager( ) «misc» +getInstance( ):AudioClipManager +play(:AudioClip) +loop(:AudioClip) +stop( ) ... FIGURE 2.1 Basic class.
📄 Page 18
Though not shown in Figure 2.1, an initial value can be indicated for a variable by following the variable’s type with an equal sign followed by the value like this: ShutDown:boolean = false You will notice that the first variable shown in the class is underlined. If a variable is underlined, that means it is a static variable. This applies to methods, too. Underlined methods are static methods. The methods in the bottom compartment are shown as follows: visibilityIndicator name ( formalParameters ) : returnType The getInstance method shown in the class in Figure 2.1 returns an AudioClipManager object. The UML indicates a void method by leaving out the ": returnType" from a method to indicate that it does not return anything. Therefore, the stop method shown in the class in Figure 2.1 does not return any result. A method’s formal parameters consists of a name and type like this: setLength(length:int) If a method has multiple parameters, commas separate them: setPosition(x:int, y:int) Two of the methods in the class shown in Figure 2.1 are preceded by a word in guillemets: <<constructor>> In UML, drawing a word in guillemets is called a stereotype. A stereo- type is used like an adjective to modify what comes after it. The con- structor stereotype indicates that the methods that follow it are constructors. The misc stereotype indicates that the methods that come after it are regular methods. Additional uses for stereotypes are described later in this chapter. One last element that appears in the class shown in Figure 2.1 is an ellipsis ( . . . ). If an ellipsis appears in the bottom compartment of a class, it means that the class has additional methods not shown in the diagram. If an ellipsis appears in the middle compartment of a class, the class has additional variables not shown in the diagram. Often, it is not necessary or helpful to show as many details of a class as are shown in Figure 2.1. Figure 2.2 shows a class that is drawn with only two compartments: When a class is drawn with only two compartments as shown in Figure 2.2, its top compartment contains its name and its bottom compart- Overview of UML ■ 9
📄 Page 19
10 ■ CHAPTER TWO AudioClipManager «constructor» -AudioClipManager( ) «misc» +getInstance( ):AudioClipManager +play(:AudioClip) +loop(:AudioClip) +stop( ) ... FIGURE 2.2 A two-compartment class. AudioClipManager instance:AudioClipManager prevClip:Audioclip ‹‹constructor›› AudioClipManager ‹‹misc›› getInstance play loop stop ... FIGURE 2.3 Simplified class. ment shows its methods. If a class is drawn with only two compartments, it simply means that its variables are not shown. It does not mean that it has no variables. The visibility indicators may be omitted from methods and variables. When a method or variable is shown without a visibility indicator, that means only that there is no indication of the method’s or variable’s visibil- ity. It does not imply that the methods or variables are public, protected, or private. A method’s parameters may be omitted if their return values are also omitted. For example, the visibility indicators and method parameters are omitted from the class shown in Figure 2.3. The simplest form of a class contains only one compartment with the class name, as shown in Figure 2.4. A one-compartment representation of a class merely identifies the class. It provides no indication about what variables or methods the class has. Interfaces are drawn in a manner similar to classes. The difference is that the name in the top compartment is preceded by an interface stereotype. Figure 2.5 is an example of an interface. Classes and interfaces are important elements of class diagrams. The other elements of a class diagram show the relationships between classes and interfaces. Figure 2.6 is a typical class diagram. The lines in Figure 2.6 indicate the relationship between the classes and interface. A solid line with a closed, hollow head such as the one in TE AM FL Y Team-Fly®
📄 Page 20
Figure 2.7 indicates the relationship of a subclass that inherits from a superclass. The class diagram in Figure 2.6 shows the abstract class Product as the superclass of the ConcreteProduct class. You can tell that it is abstract because its name is italicized. You can tell that its methods are abstract because they are also italicized. A similar sort of line is used to indicate that a class implements an interface. It is a dotted or dashed line with a closed head, as shown in Figure 2.8. The class diagram in Figure 2.6 shows that the Factory class imple- ments the FactoryIF interface. The other lines show the other types of relationships between the classes and interface. UML calls these other types of relationships associa- tions. A number of things can appear with associations to provide informa- tion about the nature of an association. The following items are optional, but this book consistently uses them wherever it makes sense. Association name. Somewhere around the middle of an associa- tion there may be an association name. The name of an associa- tion is always capitalized. There may be a triangle at one end of the association name. The triangle indicates the direction in which you should read the association. Looking at Figure 2.6, you will see that the association between the Factory and ConcreteProduct classes has the name Creates. Navigation arrows. Arrowheads that may appear at the ends of an association are called navigation arrows. Navigation arrows indi- cate the direction in which you may navigate an association. Overview of UML ■ 11 AudioClipManager FIGURE 2.4 A one-compartment class. ‹‹interface›› AddressIF getAddress1 setAddress1 getAddress2 setAddress2 getCity setCity getState setState getPostalCode setPostalCode FIGURE 2.5 Interface.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List