Object-Oriented Design Patterns - WordPress

Transcription

Object-OrientedDesign&PatternsSecond EditionCay HorstmannSan Jose State UniversityJohn Wiley & Sons, Inc.

PUBLISHER:SENIOR EDITORIAL ASSISTANT:PROJECT MANAGER:DIRECTOR OF MARKETING:SENIOR PRODUCTION MANAGER:COVER DESIGNER:COVER PHOTO:Bruce SpatzBridget MorriseyCindy Johnson, Publishing ServicesFrank LymanKen SantorHarold Nolan Corbis/Media BakeryThis book was set in Adobe Caslon by Publishing Services and printed and bound by Malloy,Inc. The cover was printed by Phoenix Color Corporation.This book is printed on acid-free paper. Copyright 2006 John Wiley & Sons, Inc. All rights reserved.No part of this publication may be reproduced, stored in a retrieval system, or transmitted inany form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States CopyrightAct, without either the prior written permission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisherfor permission should be addressed to the Permissions Department, John Wiley & Sons, Inc.,111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008.To order books or for customer service, please call 1-800-CALL-WILEY (225-5945).ISBN 0-471-74487-5Printed in the United States of America10 9 8 7 6 5 4 3 2 1

PrefaceMaking Object-Oriented Design AccessibleThis book is an introduction to object-oriented design and design patterns at anelementary level. It is intended for students with at least one semester of programming in an object-oriented language such as Java or C .I wrote this book to solve a common problem. When students first learn anobject-oriented programming language, they cannot be expected to instantly master object-oriented design. Yet, students should learn the principles of object-oriented design early enough to put them to work throughout the computer sciencecurriculum.This book is suitable for a second or third course in computer science—no background in data structures is required, and students are not assumed to have experience with developing large software systems. Alternatively, the book can be usedas a companion text in a course in software engineering. (If you need a customversion of this book for integration into another course, please contact your Wileysales representative.)This second edition is fully updated for Java 5.0, including the use of generic collections and the “for each” loop a detailed discussion of parameterized type constraints auto-boxing and varargs methods, particularly in the reflection API multithreading with the java.util.concurrent packageIntegration of Design PatternsThe most notable aspect of this book is the manner in which the coverage ofdesign patterns is interwoven with the remainder of the material. For example, Swing containers and components motivate the COMPOSITE pattern. Swing scroll bars motivate the DECORATOR pattern, and Swing borders areexamined as a missed opportunity for that pattern. Java streams give a second example of the DECORATOR pattern. Seeing thepattern used in two superficially different ways greatly clarifies the patternconcept.

ivPREFACEWithout memorable examples, design patterns are just words. In order to visualizedesign patterns, this book uses examples from graphical user interface programming.Students will remember how a component is decorated by scroll bars, and how layoutmanagers carry out different strategies. (A small and carefully selected subset of Swing isused for this purpose.)A Foundation for Further StudyAfter covering the material in this book, students will have mastered the following topicsin three subject areas:1. Object-oriented design A simple design methodology CRC cards and UML diagrams Design patterns2. Advanced Java language Interface types, polymorphism, and inheritance Inner classes Reflection Generic types Multithreading Collections3. User interface programming Building Swing applications Event handling Java 2D graphics programmingThese skills clearly form a useful foundation for advanced computer science courses. Infact, students who have completed this book will have encountered all features of the Javalanguage (but not, of course, the entire standard Java library, which is too huge for anyone person to master). One advantage of using Java is indeed that students can comprehend the entire language. Contrast that with C , a language that is so complex thatvirtually no one can truthfully claim to understand all of its subtleties.In summary: Use this book if you want your students to understand object-orienteddesign and design patterns early in the curriculum. As a bonus, your students will gain acomplete overview of the Java language, and they will be able to program simple Swinguser interfaces.Programming and Design ToolsAnother important aspect of this book is the coverage of tools. While many C programmers live their entire programming life in a large and complex integrated

Prefacevenvironment, the Java culture has embraced the use of different tools such as BlueJ,javadoc, and JUnit. Due to the reflective nature of the Java language, there are manyinteresting experimental tools. I highlight a number of them in the hope that studentswill gain an interest and aptitude in evaluating and selecting tools that fit their workingstyle.Students who learn object-oriented design also should become familiar with drawingUML diagrams. An easy-to-use and no-cost tool for this purpose, the Violet UML editor, is provided for their use. Chapter 8 of this book introduces the framework on whichViolet is based. All UML diagrams in this book were drawn with Violet.A Tour of the BookChapter 1 A Crash Course in JavaThis chapter introduces the basic syntax of Java and can serve either as a refresher or as atransition for students with a background in C . Topics covered include Defining classes and methods Objects and object references Exploring objects with BlueJ Documentation comments Numbers, strings, and arrays Packages Exception handling Common utility classes: ArrayList and Scanner Programming style guidelinesChapter 2 The Object-Oriented Design ProcessThis chapter introduces the process of object-oriented design, CRC cards, and UMLnotation. It presents a case study of a simple voice mail system to illustrate the designprocess, starting with the project’s specification and culminating in its Java implementation. Topics covered include Identifying classes and methods Relationships between classes CRC cards UML class, sequence, and state diagrams Case study

viPREFACEChapter 3 Guidelines for Class DesignUnlike Chapter 2, which took a top-down view of the discovery of classes and their relationships, this chapter focuses on the design of a single class or a small group of relatedclasses. Topics covered include Designing and implementing the interface of a class The importance of encapsulation Analyzing the quality of an interface Programming by contract: preconditions, postconditions, and invariantsChapter 4 Interface Types and PolymorphismThis chapter introduces the notation of the Java interface type, without mentioninginheritance. This approach has an important advantage: The reader learns about polymorphism in its purest form, without being burdened by technical matters such as superclass construction or the invocation of superclass methods.The chapter also introduces the Swing user interface toolkit and AWT drawing operations. It starts with the Icon interface type, which allows the placement of arbitrarydrawings in a frame.Anonymous classes are introduced as an easy mechanism for “ad-hoc” objects that implement a particular interface type. They are then put to use for Swing user interfaceactions.Up to this point, all interface types have been supplied in the standard library. The chapter ends with the design of a custom interface type. Topics covered include Frames, images, and shapes The Icon interface type The Comparable and Comparator interface types Anonymous classes User interface actions Designing interface typesChapter 5 Patterns and GU I ProgrammingThis chapter introduces the concept of patterns and covers a number of patterns thatarise in the Swing user interface toolkit and the Java collections library. Topics include Alexander’s architectural patterns Software design patterns The ITERATOR pattern as an example of a design pattern The OBSERVER pattern, model/view/controller, and Swing listeners The STRATEGY pattern and layout managers The COMPOSITE pattern, user interface components and containers The DECORATOR pattern, scroll panes, and borders

PrefaceviiChapter 6 Inheritance and Abstract ClassesThis chapter introduces the mechanics of inheritance using examples from the AWTgraphics library. There is an extensive discussion of abstract classes, a topic that manybeginners find challenging. An abstract shape class lays the foundation for the graph editor framework created in Chapter 8. Several inheritance hierarchies are examined,including the hierarchies of Swing components, geometric shapes, and exception classes.The chapter discusses advanced exception handling, including the definition of newexception classes (which, of course, requires inheritance). The chapter closes with a discussion of when not to use inheritance. Topics covered include Defining and implementing subclasses Invoking superclass constructors and methods Abstract classes and the TEMPLATE METHOD pattern The inheritance hierarchy of Swing components The inheritance hierarchy of graphical shapes in the java.awt.geom package The inheritance hierarchy of exception classes When not to use inheritanceChapter 7 The Java Object ModelThis chapter covers the Java type system in detail and introduces the important reflectioncapabilities of Java. It then moves on to a rigorous treatment of the fundamental methodsof the Object class: toString, equals, hashCode, and clone. Generics are discussed at anintermediate level, going well beyond the basics but stopping short of discussing technical minutiae. As an application of reflection techniques, the JavaBeans component modeland the implementation of JavaBeans properties are introduced. Topics covered include The Java type system, primitive types, wrappers, and array types Type inquiry and reflection Object equality and cloning Serialization Generic types Components and JavaBeansChapter 8 FrameworksThis capstone chapter culminates in the development of a graph editor framework andits specialization to a UML class diagram editor. Topics covered include The framework concept Applets as a simple framework The collections framework Application frameworks The graph editor framework

viiiPREFACEChapter 9 MultithreadingThis chapter introduces the multithreading primitives of the Java language, thuscompleting the students’ introduction to Java language semantics. The synchronizationprimitives can be challenging for students to grasp because they tightly combine severalrelated features. I first cover the Lock and Condition classes in the java.util.concurrent package, then use that background to explain the built-in locks and wait sets.Topics covered include Threads and the Runnable interface type Interrupting threads Thread synchronization The java.util.concurrent package An application: Algorithm animationChapter 10 More Design PatternsThe book concludes with a chapter that covers additional important design patterns. Asummary at the end of the chapter briefly describes additional classical design patternswhose coverage is beyond the scope of this book. Topics covered include The ADAPTER pattern Actions and the COMMAND pattern The FACTORY METHOD pattern The PROXY pattern The SINGLETON pattern The VISITOR pattern Other design patternsFigure 1 shows the dependencies between the chapters.Pedagogical StructureEach chapter begins with an introduction and listing of the chapter topics. Concepts andprinciples are presented in the context of programming examples, and many exampleprograms are printed in their entirety in the text to encourage students to read andunderstand code listings. Complete source code for all of the examples in the text isavailable from the book’s Web site at http://www.wiley.com/college/horstmann (seepages xvii–xix for a listing of the example programs that accompany this book).Throughout the chapters, there are several kinds of special features to help your students.These features are specially marked so they don’t interrupt the flow of the main material.Key concepts are highlightedwith margin notes.Margin notes highlight important topics and help students navigatethe core material of each chapter by highlighting where new conceptsare introduced.

Prefaceix1A Crash Course in Java(optional)2The Object-OrientedDesign Process3Guidelines forClass Design4Interface Types andPolymorphism9Multithreading(optional)5Patterns andGUI Programming6Inheritance andAbstract Classes7.1–7.5The JavaObject Model10More Design FrameworksF ig u r e 1Dependencies Between the Chapters7.7Generic Types(optional)7.8JavaBeans Components(optional)8.5Enhancing the GraphEditor Framework (optional)

xPREFACESpecial Topics introduce background material or advanced subjects that can be skipped.Several data structures that students in a second course may not have been introduced toare presented in these Special Topics, making them available as needed. Other SpecialTopics address features of languages other than Java that relate to the design principles inthe chapter. (See page xvi for a list of these topics by chapter.)Design Patterns are specially marked with this icon. Each design pattern is presented in astandard format that includes the context in which the pattern is useful, the solution thatthe pattern provides, and a UML diagram of the pattern elemen

Violet is based. All UML diagrams in this book were drawn with Violet. A Tour of the Book Chapter 1 A Crash Course in Java This chapter introduces the basic syntax of Java and can serve either as a refresher or as a transition for students with a background in C . Topics covered include Defining classes and methods Objects and object references Exploring objects with BlueJ Documentation .