TEAMFLY Team-Fly ® Java Enterprise Design Patterns MARK GRAND John Wiley & Sons, Inc. New York ● Chichester ● Weinheim ● Brisbane ● Singapore ● Toronto Java ™ Enterprise Design Patterns Patterns in Java TM , Volume 3 MARK GRAND John Wiley & Sons, Inc. New York ● Chichester ● Weinheim ● Brisbane ● Singapore ● Toronto 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. 10987654321 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 CONTENTS 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 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 ACKNOWLEDGMENTS 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. ABOUT THE AUTHOR 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. TEAMFLY Team-Fly ® CHAPTER 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 [...]... of 1 .3. 4 is 1 .3 Interactions numbered with a multilevel sequence number occur during another interaction’s method call The other method call is determined by the interaction’s prefix The method calls of the interactions numbered 1. 1 and 1. 2 are made during the method call of interaction 1 Similarly, interactions numbered 1. 1 .1, 1. 1.2, 1. 1 .3, occur during the method call of interaction 1. 1 Among interactions... diagram in Figure 2.24 The top-level interaction is numbered 1 During that interaction, first interaction 1. 1 is invoked Then interactions 1. 2a and 1. 2b are simultaneously invoked After that, interactions 1 .3 and 1. 4 are invoked, in that order An asterisk after a sequence number indicates a repeated interaction Consider the collaboration diagram in Figure 2.25 The collaboration in Figure 2.25 begins by... 2. 21 outMsg:OutboundMessageIF 1. 2: send() 1: receive(msg:MIMEMsg) :MessageManager 1. 1: outMsg :=parse(msg:MIMEMsg) 1. 1.2: to(:String) 1. 1 .3: from(:String) 1. 1.4: plainText(:String) builder:MAPIBuilder :MIMEParser 1. 1 .1: builder := getInstance(to:String) MessageBuilder FIGURE 2. 21 Collaboration diagram C HAPTER T WO o:ObservableIF 1: notify(o) :Multicaster 1. 1: notify(o) :ObserverIF FIGURE 2.22 Multiobject... works on Patterns in Java The first volume 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. .. diagrams indicate an object as just an empty rectangle with nothing inside it Obviously, blank objects cannot be used to identify any BusinessClass1 persists «interface» BusinessClass1PersisterIF FIGURE 2 .15 Dependency Overview of UML ■ 17 ServicePackage ▲ Uses ‹‹interface›› +ServiceIF 1 -ServiceHelper1 1 * ▲ Uses 1 Uses +Service 1 ▲ Creates 1 ▲ ServiceProxy 1 * -ServiceHelper2 FIGURE 2 .16 Package... called in the order determined by the last number in their sequence numbers Therefore, the methods of interactions numbered 1. 1 .1, 1. 1.2, 1. 1 .3, are called in that order As mentioned earlier, links represent a connection between two objects Because of that, links may not have any multiplicity indicators That works well for links that represent an occurrence of an association between a definite number... arrowhead indicates an asynchronous method call An asynchronous method call returns to its caller immediately, while the method does its work asynchronously in a separate thread The collaboration diagram in Figure 2 . 31 shows an asynchronous method call CompositeTransactionLogic 1. 1: register(wrap1) 1. 2a: startTransaction( ) 2 .1: commit( ) 1. 1 .1: synchronize( ) 1. 1.2: status1:=getStatus( ) 1. 1.2/[all... are indicated by listing them at the left side of the interaction followed by a slash (/) and the rest of the interaction The collaboration diagram in Figure 2 .30 contains an example In Figure 2 .30 , the interaction labeled 2.1a .1 cannot start until interaction 1. 1.2 finishes If an interaction must wait for more than one additional interaction to finish before it starts, they all appear before the slash,... other interactions finish All interactions have an implicit precondition that they cannot start before the directly preceding interaction finishes An interaction numbered 1. 2.4 cannot start until the interaction numbered 1. 2 .3 completes Some interactions are required to wait for additional interactions to complete before they can start Such additional predecessor interactions are indicated by listing... called by an interaction Consider the collaboration diagram in Figure 2.28 :EMailEncrypter 1: logMessageReceipt(plainText:MimeMsg) {concurrency=guarded} :Logger FIGURE 2.27 Synchronized method call 24 ■ C HAPTER T WO :EMailEncrypter 1: logMessageReceipt(plainText:MimeMsg) {concurrency=guarded:out} 1. 2: getSessionInfo() :Logger 1. 1: print(:Date) 1 .3: print(message:String) :Logger out:PrintStream FIGURE . programming (Computer science) I. Title. QA76. 73. J38 G72 20 01 005. 13 & apos ;3 dc 21 20 010 45 611 Printed in the United States of America. 10 98765 432 1 Acknowledgments vii About the Author viii Chapter 1 Introduction. 99 Redundant Independent Objects 10 9 Prompt Repair 11 5 Mobile Agent 11 9 Demilitarized Zone 12 9 Process Pairs 13 3 Chapter 6 Distributed Computing Patterns 13 7 Object Identifier 13 9 Registry 14 9 Protection. Team-Fly ® Java Enterprise Design Patterns MARK GRAND John Wiley & Sons, Inc. New York ● Chichester ● Weinheim ● Brisbane ● Singapore ● Toronto Java ™ Enterprise Design Patterns Patterns in Java TM ,