<<

APPENDIX

A - Quick Reference

This appendix is a reference of the Gang-of-Four , intended to jog your memory about how the patterns work. Ironically, the original Gang-of-Four presentation was this brief, but they expanded things in the book to make it more accessible. Once you know the patterns, however, brevity is good. This catalog probably won't be of much use if you don't already have some familiarity with the patterns, however. A lot of the material you'd find in an introductory- discussion is either missing or condensed in this appendix. Though I've followed the Gang-of-Four organization (alphabetical by category), I have deliberately not followed the Gang-of-Four format for the pattern description itself. In partic• ular, I've restated their "intent" section to make it more understandable. I've also used stripped• down examples, and my examples are not the same as the Gang-of-Four examples. In particular, since most of us aren't doing GUI work, I've tried to eliminate GUI-related example code. I've tried to make up for some of this brevity by listing places where the design patterns are found in the Java packages so you can see how they're applied in practice. (Some patterns don't appear in Java, in which case the "Usage" example will say so). Also, you can find detailed code similar to my stripped-down examples in one of the volumes of Chan, Lee, and Kramer's The Java Class Libraries (Addison-Wesley, various editions) or in the Java documentation or tutorials available on the Sun web site. I've played fast and loose with the code in the interest of saving --I've omitted required import statements, access privileges, exceptions, and so on. The formatting isn't ideal in places. I'm assuming you know what you're doing in the Java-programming department and are more interested in the clarity of the example than in having cut-and- paste code. The code won't always compile cleanly as it stands. Finally, I've said a few things in these notes that you may find shocking if you haven't read the rest of the book or some of my other work-things such as "objects must be responsible for building their own user interfaces." I simply have no room to explain this sort of thing in a quick reference; you have to read the rest of the book.

347 348 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

1. Rather an odd thing to say, since the page isn't blank at all-it contains the text "This page intention• ally left blank" -but imagine that it's blank. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 349

Creational Patterns The creational patterns are all concerned with object creation (fancy that!). Most of them provide ways to create objects without knowing exactly what you're creating (beyond the interfaces supported by the created objects). Programming in terms of interfaces rather than concrete-classes is essential if you intend to write flexible, reusable code. My rule of thumb is that as much as 80 percent of my code should be written in terms of interfaces. 350 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Abstract Factory Create objects knowing only the interfaces they implement (without knowing the actual class). 'JYpically, create one of a "family" of objects (one of several kinds oflterators, one of several kinds of graphical widgets, and so on).

Abstract Factory: to the actual factory. User Concrete Factory: Implements ~ Client 1 Abstract -"'- I Product,. IIMIJtor •lntllrface• the Abstract Factory interface Collection •lntertacs• I .. Abstract .,. .,.. -- .... ""'<,. +hasNext 0 ;boolean to create a specific class of +lteraiDr 0 :lterator Facto'! ' Abstract J H16xl O: Object object. - - - "', Factory , HflmOWI O: void ~---"'( I Abstract Product: The sort /:J. Concrete/ \ Concrete t 1 /:J. PJCtory 1 Product t of product that the Abstract t t-- Unkedlist LinkedUsUterator -,t Factory creates. t + 0 :lterator +llasNext 0 :boolean t Concrete Product: The actual I ~a~ ~extO : Object t I +remove O: void t object (whose class you don't I t know) created by the factory. I t Tree Treelterator •anonymous• L-- J Client: Uses the created objects +iterator 0 :Herator +llasNext 0 :boolean only through their interfaces. ~8~ ~extO : Object +remove O: void

What Problem Does It Solve? X If the produ,ct doesn't do what you want, you may have to change the Abstract Product Abstract Factory makes it easy to create interface, which is difficult. (You have to and manipulate objects without knowing change all the Concrete Product definitions.) exactly what they are. (This example uses an Iterator-it doesn't care what kind.) This way, it's easy to add new sorts of concrete products Often Confused With to the system without changing any of the code Builder: Builder's Director may use an Abstract that uses those products. Factory to create Builder objects, but the point Abstract Factory also makes it easy for of Builder is that the Director doesn't know your code to operate in diverse environments. what it's building. The system creates a unique Concrete Factory Factory Method: A Factory Method-an unfor• (which creates unique Concrete Products) tunate choice of pattern name on the part of for each environment, but since you use the the Gang of Four-is an abstract method that a interface, you don't actually know which envi• subclass overrides. The Abstract-Factory method ronment (or which Concrete Product) you're that creates objects is only rarely a Factory using. Method.

Pros (v) and Cons (a) See Also t/ The anonymity of the Concrete Factory and Singleton, Factory Method, Builder Product promotes reuse--the code that uses these objects doesn't need to be modified if the Factory produces instantiations of different classes than it used to do. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 351

Implementation Notes and Example Collection is the Abstract Factory, Iterator interface Collection is the Abstract Product, Tree is the Concrete { Iterator iterator(); Factory, and the anonymous-inner-class II ... Iterator implementation is the Concrete Product. interface Iterator Abstract Factory has many variants, prob• { boolean hasNext(); ably the most common of which is a Concrete Object next(); Factory that comprises its own interface-no II ... '~bstract Factory" interface as such exists. This Concrete Factory is typically a Singleton. The class Tree implements Collection { public Iterator iterator() methods of the class effectively comprise { return new Iterator() the Abstract Factory interface. { II Implement Iterator interface class SingletonFactory II here (to traverse a Tree). { private static instance=newSingletonFactory(); II (See description of Iterator public static SingletonFactory instance() II pattern for implemenation.) { return instance; }

void factoryOperationl(){l* ..• *l} class User II uses only interfaces void factory0peration2(){1* .•• *1};

public void operation( Collection ) A similar, though more abstract, example { Iterator i = c.iterator(); while( i.hasNext() ) is described in the entry for Factory Method. doSomethingWith( i.next() ); No reason exists why, in the no-Abstract• Factory variant, the Concrete Factory cannot create a user interface that allows the physical user to select which of several possible concrete products to create. Consider a drawing program whose "shape" factory creates a user interface showing a palate of possible shapes. The user can then click a shape to determine which Concrete Product (shape derivative) to create in response to a newShape() request.

Usage (Collection c) Collection and Iterator are the Abstract Factory { Iterator i = c.iterator(); and Product. Concrete Factories and Products II ... are anonymous.

ButtonPeer peer = Toolkit is both a Singleton and an Abstract Toolkit.getDefaultToolkit(). Factory. Most of the methods ofToolkit are createButton(b); abstract, and getDefaultToolkitO returns an unknown derivative of Toolkit. No need exists for an Abstract Factory interface per se. URL home= new URL("http:llwww.holub.com"); URL is a concrete URLConnection factory, and URLConnection c = home.getConnection(); URLConnection is an abstract InputStream factory, InputStream in = c.getinput(); so URLConnection is both an Abstract Product and an Abstract Factory, depending on context. URL, URLConnection, and InputStream are interfaces by use, not by declaration. 352 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Builder Separate the construction of a complex object from its representation so that the same construction process can create different representations without having to modify the constructing object.

Director: Builds an object without what it's building. Client ~':"~,_ knowing exactly I I -.,...,..---, Builder Cll8ttlmllr.ExporW I }----- .,,.,.,.,. Builder: Interface used by the I .... Builder Oirettor , ~ -T .... - w " ~me {!ext string} Director to do the construction. I Customer ',•USB• ~ (Bddr: string} :- - ~~ - - -> Concrete Builder: Actually builds Name, Address I ' ' the product by following directions +exportUI (b: Exporter) I I ' ' ~ given by the Director. Typically I ' ' I Concrete Builder I ' , Product I created externally (by the Client) I ' I or by an Abstract Factory. HTMLExporter String I ~~>I I I +addName (text: String) I Product: The object built by the +addAddress (addr: String) Builder under the direction of !cmate?" +gotProduct( ): String ------JI I the Director. I JComponentExporter ------1 +addName (text: String) +addAddruss (addr: String) ~~· ~ JComponent I +getProduct 0:JComponent

What Problem Does It Solve? Pros (V') and Cons (x) It's desirable to separate business logic from UI V' Builder nicely isolates the representation logic, but in an 00 system you cannot expose of an object from the associated "business" implementation details. A well-done class defi• logic, making it easy to add new (or change) nition will not have "get" methods that return representations of an object without modi• state information, so an object must build its fying business logic. own UI. Nonetheless, it's sometimes necessary X A change in the Builder interface mandates for an object to build more than one represen• changes in all implementing classes. tation of itself, and it's undesirable to clutter up the business-logic code with the details X It's awkward to represent some UI elements needed to build multiple representations. cleanly in all representations (for example, Builder solves this problem by putting HTML vs. Swing). the representation-specific code into a Builder object that's distinct from a Director ("busi• Often Contused With ness") object. Builder also easily lets you add Bridge: An application building a UI using representations later without impacting AWf is a Director-the actual representation existing code at all. is unknown to the application. In this way, Non-UI applications: credit-card process• AWf reifies both Builder and Bridge. ing; for example, every credit-card-payment processor requires a different protocol, with Visitor: A visitor could build a UI by visiting identical information presented in different every element of a . It is "pulling" ways. Builder separates you from the needs information for UI construction from the of the credit-card processor, letting you build model rather than having that information a packet of information without needing to "pushed" onto it. know which processor will receive that infor• mation. The organization of the data is hidden See Also from you in the "concrete builder" that you talk to via a public, processor-independent, interface. Bridge, Visitor APPENDIX A DESIGN-PATTERN QUICK REFERENCE 353

Implementation Notes and Example The createUI () method is passed a Builder class Customer that could be an HTMLExporter (that creates an private Address address; HTML representation) or a JComponentExporter Private String name; (that produces a JComponent). The Director public void exportUI ( Exporter b ) object doesn't know which of these products { b.addName(name); it is building-it just calls interface methods. b.addAddress(address. toString()); The Client object that's driving this process I I ... does know what it's building since it created the Builder. Consequently, it's reasonable for it to public interface Exporter extract the correct product. { void addName(String text); void addAddress(String addr); You could get better abstraction by using I I .•• an Abstract Factory to create the Builder objects rather than new. By the same token, if all output was going to a file, you could add a print• class HTMLExporter implements Customer. Exporter VoursefToFile(String name) method to the { I I Implement Builder methods here. This Builder interface; the Director could call that I I Implementation creates an HTML method at an appropriate time, and the Client I I representation of the object. wouldn't have to extract anything; it would just I I •.. supply a filename. public String getProduct() Builder implementations could be public { I I Return HTML String. } inner classes of the Director. I'd probably do it that way unless I expected that Builders would class JComponentExporter implements Customer. Exporter be defined elsewhere in the code. { JComponent product; The Director is "pushing" information into I I Implement Builder methods here. This the Builder. Consequently, you have no need I I Implementation creates a ]component for accessors (get methods) in the Director, I I that represents the object. and the coupling between the Builder and I I .•• Director is very light. In general, accessors public JComponent getProduct () violate the integrity of the object by exposing { return product; } implementation detail. Avoid them. class Client Employee director; I I .•• public void addYourUITo(JPanel someWindow) { Customer. Exporter b = JComponentExporter(); director. exportUI ( b ) ; someWindow.add( b.getProduct() ); }

Usage URL url =new URL{"http:llwww.holub.com"); This code comprises a Director. It uses URLConnection connection = url.openConnection(); Abstract Factory (URLConnection) to get a connection.setDoOutput( true ); Builder (the OutputStream), which builds an connection.connect(); HTTP packet. The Director doesn't know OutputStream out = connection.getOutputStream(); that it's building an HTTP packet, however. while( c = getCharacterFromSomewhere() ) (If an ftp: I I URL had been specified, it out.write( c ); would be building an FTP packet.) The out. close(); close() call, instead of getting the product, just sends it off. 354 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Factory Method Let subclasses decide which objects to instantiate.

Creator: Defines a method that needs to create an object whose actual type is public w id doSom9111ingO { E lement e = createDefaultEiementO; unknown. Does so using abstract-method //. .. I call. protected Element createOefaultEiementO { return new ElementO; Concrete Creator: Subclass that overrides I the abstract object-instantiation method to create the Concrete Product. BuslnessObject ~~ Element Product: Interface implemented by the + doSomethlng 0 / Product created product. Creator accesses the #create0efaul1flement 0 :Element / CreatDr ~ Concrete Product object through this ~r- ' ... ,.~- ---..~. .. I interface. I Fac ' Me Concrete Product: Object used by the Concreto ., ~, =~_ - - \ ) Concrete Cma!Dr ., .. -- , Pro

What Problem Does H Solve? *C Inheritance-based framework , in which Factory Methods are usually This pattern is useful when you can do all (or found, are not the best way to achieve reuse. most) of the work at the superclass level but Generally, it's best if a framework class can want to put off deciding exactly which sort simply be instantiated and used directly, be working on until runtime. of object you'll without forcing a programmer to create a (You'll manipulate objects that a derived-class subclass to make the superclass useful. an interface that you define.) creates through Implementation inheritance should be It is often the case that a superclass object reserved for situations where you need to needs to create worker objects of some default modify superclass behavior to perform type, but the superclass can work equally well in an unusual way. using worker objects that are extensions of the original type. This pattern lets you create specialized worker objects in a specialized Often Confused With subclass. Abstract Factory: The Concrete Factory can This way of doing things is often useful use Factory Method to create Concrete Prod• when you create an implementation-inheri• ucts. The creational method does not have to tance-based "framework" that you expect use this , though. A method is users to customize using derivation. not a Factory Method simply because it manu• factures objects. (I've seen the term misused in Pros (tt) and Cons (•) the Java documentation, among other places.) In Factory Method, a derived-class override tl Easy to implement when a full-blown makes the object. Abstract Factory is overkill. • This pattern forces you to use implementa• See Also tion inheritance, with all its associated maintenance problems. Abstract Factory, Template Method APPENDIX • A DESIGN-PATTERN QUICK REFERENCE 355

Implementation Notes and Example The negative side to this architecture is that you often must modify the superclass ifyou add public class BusinessObject a subclass. The java. awt. Toolkit Abstract { public void doSomething() { Element e = createDefaultElement (); Factory overcomes this problem while still using I/ ... an abstract-superclass architecture by instanti• ating objects with Class. forname() rather than protected Element createDefaultElement () an abstract-method call. This structure is still { return new Element(); Factory Method, since the decision about which } class to instantiate is deferred to runtime-it's just not a subclass that's making the decision. public class Element It is often inappropriate to use Factory { public void f(){!* ... */} Method if the only method provided by the } subclass is the Factory Method itself. You're public class SpecializedBusinessObject adding complexity with little commensurate { protected Element createDefaultElement() benefit. { return new SpecializedElement (); Never leverage the fact that protected } grants package access in Java. The create• private class SpecializedElement extends Element DefaultElement () method is protected only { public void f(){ /* ... */ } because I expect it to be overridden by a } subclass (otherwise it would be private). This method should not be called from anywhere You can sometimes customize superclass other than the BusinessObject superclass. The behavior by providing nonstandard objects for it language, unfortunately, grants package access to work with. In this example, a specialized form to protected members, but it's best to pretend of a business object is created by extending the that package access is not possible. generalized version in such a way that it provides This pattern is so trivial as to almost not be a specialized element rather than the default worth calling it a pattern. It's more interesting in element. C++, where it's called a virtual constructor and is implemented by overriding operator new().

Usage public class MarkupPanel extends JEditorPane In Swing's JEditorPane, various HTML { public MarkupPanel() elements are displayed as "views." { setEditorKit( When a parser recognizes an HTML new HTMLEditorKit() element, it requests a "view" that { public ViewFactory getViewFactory() renders the component. You specify { return new CustomViewFactory(); a custom representation of an HTML } element by providing a derived-class } override of a create() method that ) ; returns a component of your choice. Component is the Product. The private class CustomViewFactory (anonymous) implementation of extends HTMLEditorKit.HTMLFactory Component is the Concrete Product. { public View create(Element e) The MarkupPanel is the Creator, and { return new View() the CustomViewFactory is the Concrete { protected Component createComponent() Creator. createComponent() is the Factory { return new Component(){/* ... */}; Method. Similarly, getViewFactory() is a } Factory Method that produces custom } view factories. A subclass specifies } alternative view factories by overriding } getViewFactory(). 356 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Prototype Create objects by making copies of (cloning) a prototypical object. The prototype is usually provided ?~an external entity or a Factory, and the exact type of the prototype (as compared to the interfaces 1t rmplements) may not be known.

Prototype: Interface of object to copy; must define a mechanism for cloning itself. ConcretePrototype: Object that's copied; implements cloning mechanism. Client: Creates a new object by asking the Prototype for a clone.

What Problem Does It Solve? example). Rather than repeatedly going through the expense of creating an object, 1. Allows you to create several objects of the create a single prototype and copy it same type, even if you don't know exactly multiple times. what that type is. 2. In Abstract Factory, information needed to Pros (v) and Cons (x) initialize the Concrete Product (constructor arguments, for example) must be known at t/ You can install a new concrete product into compile time. Most Abstract Factory reifica• a Factory simply by giving the Factory a tions use the default, no-arg constructor. prototype at runtime. Removal is also easy. When you use Abstract Factory to make t/ Prototype can reduce object-creation time. objects that must be in a nondefault state, t/ Abstract Factory forces you to define classes you must first create the object and then with marginally different behavior using modify it externally, and this external modi• subclassing. Prototype avoids this problem fication may happen in many places in the by using state. When an object's behavior code. It would be better to create objects changes radically with state, you can look with the desired initial (nondefault) state at the object as a dynamically specifiable and simply copy those objects to make addi• class, and Prototype is your instantiation tional ones. You may use Abstract Factory to mechanism. make the prototype object. X You must explicitly implement clone (), 3. Sometimes objects will be in only a few which can be quite difficult. Also, think about possible states, but you have many objects deep-vs.-shallow copy issues. (Should you in each state. (The Gang of Four describe a copy a reference, or should you clone the Note class in a music-composition system; referenced object?) Finally, sometimes the many instances of whole-note, half-note, clone method should act like a constructor and quarter-note objects exist-all whole and initialize some fields to default values. notes are in an identical state. A clone of a list member cannot typically be 4. Sometimes classes are specified at runtime in the list, for example. and are created with dynamic loading (for example, Class. forname("class. name")) or a similarly expensive process (when initial See Also state is specified in an XML file, for Abstract Factory, State APPENDIX A DESIGN-PATTERN QUICK REFERENCE 357

Implementation Notes and Example In this example, HTTPHandler talks asynchro• class AsynchronousStorage nously to a remote host using H'ITP, and { private Handler protocol; FTPHandler talks using FTP. One handler exists public AsynchronousStorage( Handler protocol ) for each communication; several handlers can { this.protocol = protocol; be active simultan~ously, each talking to their } respective hosts. Prototype is used to decouple the protocol from the AsynchronousStorage void store( Collection data, URL host ) class. The User class decides which protocol to { byte[] bytes = new byte[128]; use and then passes an appropriate handler I I •.• to the Asynchronous Storage object, which uses Handler handler= (Handler )protocol. clone(); handler. sendData(bytes, host); clones of the prototype to do the actual work. You cannot use new to implement a "clone" method. The following code won't work: Class Grandparent interface Handler extends Cloneable { public Grandparent(Object args ){I* •. . *I} void sendData(byte[] data, URL host); Base myClone(){ return new Base(args);} Object clone(); Class Parent public Parent(){ super("arg");} class HTIPHandler implements Handler Derived myClone(){return new Parent(args)} { public void sendData(byte[] data, URL host) { I I Send data asynchronously to Class Child I I host using HTTP protocol, creating { public Child(){ super(); I I background if necessary I* inherit the superclass myClone *I

public Object clone(){ 1* .•. *1} I I •.. Grandparent g = new Child(); I I ... class FTPHandler implements Handler g.myClone(); II Returns a Parent, not Child! { public void sendData(byte[] data, URL host) { I I same as above, but use FTP protocol Using Java's clone() solves this problem by } getting memory from super. clone (). public Object clone(){ I* •.. *I } class User private Collection theData; private AsynchronousStorage dataStore = new AsynchronousStorage( new HTIPHandler() ) ; public void flush() { dataStore.store(theData, new URL(/* ... *1)); }

Usage (Not used) Prototype is used in the implementations of several classes but not in the external interfaces to any of the Java classes. You do see it in the Bean Box application that demonstrates GUI -style JavaBeans. When you customize an object and put it on the palate, you're creating a prototype. When you drag the customized object from the palate to the dialog box that you're constructing, you're making a copy of the prototype. 358 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Singleton A class with a constrained number of instances (typically one). The instance is globally accessible.

Singleton: The object being created; defines a Singleton class-level (static) get-instance method that -~ returns the instance. The class-level get• + •static• instance 0 : Singleton •static• -Instance +OtherMethods 0 instance method may create the object if ... necessary...... public static synchronized Singleton instanceO { if( instance == null ) instance =new SingletonO return Instance;

What Problem Does It Solve? Often Confused With Programs often have a need for single-instance Utility: A Utility is a class comprised solely objects. Objects, for example, may represent a of static methods, the purpose of which is to single database, a single company, and so forth. provide a grab bag of global methods that often compensate for some deficiency in the Pros (v) and Cons (x) language or libraries. Examples include Java's Math and Arrays utilities. tl' Better than a global object in that access is controlled, and the global namespace isn't Singleton can be implemented the same way cluttered with hard-to-find objects. as Utility-as a class made up solely of static methods. That is, when all fields of a class are tl' Singleton guarantees that the object is static, the class is effectively an object: It has created (and destroyed) only once-essen• state and methods. The main disadvantage to tial when the Singleton manages a global this everything-is-static approach is that you resource such as a database connection. can't change the behavior of a Singleton using X Easy to abuse. A Singleton called Globals derivation. that contains nothing but public variables is an abomination. (A Singleton containing See Also global constants is reasonable if the values of the constants need to be initialized at Abstract Factory runtime. If the values are known at compile time, use an interface made up solely of static final fields.) X Another common abuse of Singleton defines a User object that contains all the user-interface code. In a properly done 00 system, objects must be responsible for building their own user interfaces. Similarly, you should not have a "system" or "main'' singleton. The system is the entire program, not a single object. System objects are what Arthur Riel calls god classes (in his book Object-Oriented Design Heuristics, (Addison-Wesley, 1996). Avoid them. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 359

Implementation Notes and Examples Use the Singletonl form when you can't Class Singletonl create the object at class-load time (for example, { private static Singleton instance; you didn't have information that's determined private Singletonl () by program state or is passed to the creation { Runtime.getRuntime().addShutdownHook method). ( new Thread() You must synchronize the instance() method { public void run() of Singletonl as shown. "Clever" ways to elimi• { /* clean-up code here */ nate synchronization such as "double-checked } locking" don't work. (Period. Don't do it!) Use the Singleton2 or Singleton3 form ) ; when possible; synchronization is not required public static synchronized Singleton instance() during access. (The JVM may load the class at { if( instance == null ) any time, but it shouldn't initialize the Class instance = new Singleton(); object until first use (Java Language Specifica• return instance; tion, 12.4.1); static initializers shouldn't execute until first use. Call addShutdownHook () in the constructor class Singleton2 when program-shut-down cleanup activities { private static final Singleton instance = (such as shutting down database connections new Singleton2 (); in an orderly way) are required. Do not use a public static Singleton instance() { return instance; finalizer, which may never be called. } A private constructor prevents someone I I ... from saying new Singleton (), thereby forcing I /other than creating object in static access through instance (). //initializer, is identical to Singletonl You have no requirement that only one instance of the Singleton exists, only that the class Singleton3 number of instances are constrained and that { static Type allFields; access to the instances are global. For example, static Type allOperations (); a DatabaseConnection.getlnstance() method I I No instance() method, just use the may return one of a pool of database connec• I I class name to the left of the dot. tions that the Singleton manages. In UML, the role associated with the Singleton is usually also the class name.

Usage

Image picture = The Toolbox is a classic form of Singletonl in the Toolbox.getDefaultToolbox().getimage(url); "Examples" section. getDefaultToolbox() returns a Toolbox instance appropriate for the operating system detected at runtime.

Border instance = Manages several Border instances, but only BorderFactory.createBevelBorder(3); one instance of a Border object with particular characteristics (in this case, a three-pixel beveled border) will exist, so it's a Singleton. All subsequent requests for a three-pixel beveled border return the same object.

Class classObject = There's only one Class object for a given class, class.forName("com.holub.tools.MyClass"); which effectively contains all static members. 360 APPENDIX. A DESIGN-PATTERN QUICK REFERENCE

2. Here, we have the second reification of the this-page-intentionally-left-blank pattern. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 361

Structural Patterns The structural patterns concern themselves with the organization of the program. I think of them as static-model patterns. Their intent is always to organize classes so that certain structural ends can be achieved. For example, the purpose of Bridge is to organize two subsystems in such a way that one subsystem can change radically (even be replaced entirely) without affecting the code in the other subsystem. The whole point of this organization is that you can make changes to the program without having to change the dynamic model at all. 362 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Adapter Make a class appear to support a familiar interface that it doesn't actually support. This way, existing code can leverage new, unfamiliar classes as if they are existing, familiar classes, elimi• nating the need to refactor the existing code to accommodate the new classes.

Adaptee: An object that doesn't support pullliclllljeIO; ~ .Mapte , --Cla$s .... v OlljldlnpuiSlrNm ---~-", A.r;bp!Sr ... ).. __r~~ Adapter: The class that makes the .... _... __ ..adlllijeel 0 Adaptee appear to support the Target +WrlloOI>jociO; -.ro4MJtt():Obfm:t.. - Alliin~-~ ../ ~ Ot;ecl ..... r- -r;,~- //.._ .-o:vo~~~ interface. Class Adapters use derivation. ' ... Adapt~_.,.,., ,; 1 ~a;~ter Object Adapters use containment. r ~ -----I -o.. - * -.!(): Objecl lPIio0$<1nex1() - •1 JOI!Jm n .read0b)o<10; --o : vo~c~ J

What Problem Does It Solve? an Object or Class Adapter is best. It's a main• tenance problem to have both. 1. A that you're using just isn't working out, and you need either to rewrite it or to X Difficult to implement when the library is buy a replacement from a third party and designed poorly. For example, java. io. Input• slot this replacement into your existing Stream is an abstract class, not an interface, code, making as few changes as possible. so you can't use the Class- to create a RandomAccessFile that also supports 2. You may need to refactor a class to have a the InputStream interface (you can't extend different interface than the original version both RandomAccessFile and InputStream). You (you need to add arguments to a method or can use Object Adapter, or you can refactor change an argument or return-value type). the code to make InputStream an interface (as You could have both old-style and new-style it should have been) and then implement that versions of the methods in one giant class, interface in an AbstractlnputStream that has but it's better to have a single, simpler class all the functionality now in InputStream. (the new one) and use Adapter to make the Collections do it correctly. new object appear to be one of the old ones to existing code. 3. Use an Adapter to make an old-style object Often Confused With serialized to disk appear to be a new-style Mediator: Mediator is the dynamic-model object when loaded. equivalent of Adaptor. Adapters are passive, passing messages to single Adaptees. Mediators Pros (11"') and Cons (x) interact with many colleagues in complex ways. Bridge: Adapters change interfaces. Bridges ttl Makes it easy to add classes without isolate subsystems. Adapters are little things; changing code. Bridges are big. X Identical looking Object and Class Adapters Decorator: The encapsulated object in Deco• behave in different ways. For example, new rator has the same interface as the container. ObjectAdapter(obj) andnewClassAdapter(obj) Decorator modifies the behavior of some are both supported; the Object Adapter simply method or adds methods, but otherwise wraps obj, but the Class Adapter copies the looks exactly like the wrapped object. Object fields of obj into its superclass component. Adapters have different interfaces than the Copying is expensive. On the plus side, a Class wrapped object and don't change its behavior. Adapter is an Adaptee, so it can be passed to methods expecting an object of the Adaptee class and also to methods that expect the See Also Target interface. It's difficult to decide whether Mediator, Bridge, Decorator APPENDIX. A DESIGN-PATTERN QUICK REFERENCE 363

Implementation Notes and Example Objectlterator is a Class Adapter that class Objectiterator extends ObjectinputStream adapts an ObjectlnputStream to implement implements Iterator the Iterator interface. This way, you can use private boolean atEndOfFile = false; existing methods that examine a set of objects public Objectiterator(InputStream src) by using an Iterator to examine objects directly throws IOException from a file. The client doesn't know or care super(src); whether it's reading from a file or traversing a Collection of some sort. This flexibility can be public boolean hasNext() useful when you're implementing an Object { return atEndOfFile == false; that can overflow to disk, for example. } public Object next() More to the point, you don't need to write two { try versions of the object-reader method, one for { return readObject(); files and one for collections. } WrappedObjectlterator is an Object catch( Exception e ) Adapter version ofObjectlterator that uses { atEndOfFile = true; containment rather than inheritance. return null; The Class Adapter, since it is an Object• InputStream that implements Iterator, can be used by any method that knows how to public void remove() use { · throw new UnsupportedOperationException(); either ObjectinputStream or Iterator. The } Object Adapter, since it encapsulates the input stream, cannot be used as an Objectlnput- class WrappedObjectiterator implements Iterator Stream, but you can use the input stream for a private boolean atEndOfFile = false; while, temporarily wrap it in a WrappedObject• private final ObjectinputStream in; Iterator to extract a few objects, and then pull public the input stream out again. WrappedObjectiterator(ObjectinputStream in) The two implementations require about { this.in = in; the same amount of work so it's a judgment call } which one is best. It all depends on what you're public boolean hasNext() using it to do. { return atEndOfFile == false; } public Object next() { try { return in.readObject(); } catch(Exception e){/* as above */}

public void remove() { throw new UnsupportedOperationException(); }

Usage InputStream in = new StringinputStream("hello"); Adapter lets you access a String as if it were a file (InputStream). Similar adapters include ByteArrayinputStream,CharArrayReader,Pipedinput• Stream, Piped Reader, and StringReader. Don't confuse these adapters with the Decorators in java.io {BufferedinputStream, PushbacklnputStream, and soon). 364 APPENDIX . A. DESIGN-PATTERN QUICK REFERENCE

Bridge To decouple subsystems so that either subsystem can change radically without impacting any code in the other one, put a set of interfaces between two subsystems and code to these interfaces.

Abstraction: A subsystem• independent portal into ~ --- Bridge javuqi.Comec:Uon I subsystem-specific code. I SmariConnection ...... +CrUieS-0 ~0- Implementor: An interface used ~-(-URL) ' ' Allsiiatlioo ... by the Abstraction to talk to a ' ' ~ ' ', 1 hnJ)Iemenlor /j subsystem-specific implementa• ' I J com.holub.-.connecllon I ' ' I tion. Typically is also the Abstract ' ' I +setUfetime( max\Jfetlme) I ', l~;'~ Product of an Abstract Factory. L com.holub.OropableConnecllon J_ ------' - "(; ~ Refined Abstraction: Often I Ref-ned Abslractioo , Coo<:rote 1+II OtilyllnOrop( lisloner ) \ hnule1nentor omitted, a version of the Abstrac• tion, customized for a particular application. com.oracle.OracleConnoclion Concrete Implementor: A +creoteS1lltement0 ~ ~~ ~ +prepareS131ement0 subsystem-specific implementa• ... ------tion of the Implementor.

What Problem Does It Solve? Often Confused With Often used to achieve platform independence. Bridge is more of an architecture than a design Application-specific code on one side of the pattern. A Bridge is often a set of interfaces and bridge uses platform-dependant code on the classes (called abstractions, unfortunately• other side. Reimplement that interface, and they're typically not abstract) that contain the "business" logic doesn't know or care. references to objects that implement a plat• Change the business logic, and the platform• form-independent interface in a platform• specific interface implementations don't care. dependant way (Adapters). The Adapters are Often, you'll combine Bridge and Abstract typically created by the Abstraction object Factory so that the Factory can supply the using a Singleton-based Abstract Factory. correct set of implementers at runtime, further Adapter: Bridges separate subsystems, and isolating the two sides of the bridge. Examples Adapters make objects implement foreign of Bridge in Java are AWf and JDBC. interfaces. A one-interface bridge looks like a Class Adapter, however. Pros {11") and Cons {x) Facade: Facade simplifies the interface to a t1 In a pure inheritance model, you'd have a subsystem but may not isolate you from the superclass that implemented some behavior details of how that subsystem works. Changes and subclasses that customized this behavior made on one side of the facade might mandate for a specific platform. In Bridge, the super• changes both to the other side of the facade class is effectively replaced by an interface, and to the facade itself. so the problems associated with implemen• tation inheritance are minimized, and the See Also total number of classes are reduced. Abstract Factory, Singleton, Adapter, Facade, X It's difficult to implement interfaces so that Mediator each implementation behaves identically. Java's AWf Bridge implements windowing components for different operating envi• ronments, but the Motif implementation behaved differently on the screen than the Windows implementation. APPENDIX. A DESIGN-PATTERN QUICK REFERENCE 365

Implementation Notes and Example The abstraction classes (SmartConnection, class SmartConnection PersistentConnection, and DropableConnection) String username, password; use the Bridge interface (java..Connection) java.sql.Connection connection; to talk to the implementation classes (Oracle• II ... Connection,SQLServerConnection). public void connect(String databaseURL) The two sides of the Bridge can change throws Exception independently. For example, I can change Class. forName( databaseURL ) . newlnstance(); OracleConnection radically, and the classes on the other side of the Bridge (SmartConnection, Connection connection = null; for example) are completely unaware of that Statement statement = null; II ... change. This isolation is possible because connection = Factory is used to create the Concrete Imple• DriverManager .getConnection( menters. databaseURL, username, password ) ; I can even support additional databases (by extending java. sql. Connection) without affecting the other side of the Bridge. By the same token, I can modify the SmartConnection class PersistentConnection extends SmartConnection class (and its subclasses) and even add addi• long maxlifetime; tional subclasses, without impacting the other public void setlifetime(long maxlifetime) side of the bridge (the java. sql. Connection { I I Arrange for connection to time I I out after lifetime expires. implementers). Note that the Bridge completely isolates the subsystems from each other. The Client class knows only about the abstraction classes. class PooledConnection extends SmartConnection A Bridge is often very large. The JDBC Bridge public void notifyOnDrop(Runnable dropped) consists of many Implementor interfaces and { I I Arange to call dropped. run() associated Concrete Implementations, and I I when connection is dropped. some of these interfaces are very large.

I I------class SQLServerConnection implements java. sql. Connection I I Implementation that support SQL Server I I interface. class OracleConnection implements java.sql.Connection { I I Implemenation that supports Oracle's interface. 366 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Composite Organize a runtime hierarchy of objects that represent container/content (or whole/part) relation• ships as a collection of objects that implement a common interface. Some of the implementers of this interface define stand-alone objects, and others define containers that can hold additional objects, including other containers.

Component An interface or abstract class that repre• container . • ~ subelements sents all objects in the FGrm ... Ellmllllt~ hierarchy. +add ( subelement Bement) -position: Rectangle +~o (surface: Graphics) ..aement(posltlon: Rec1angle) Composite: A Component ~surface: Graphics) Component that can hold other Compo• I \Composite +I'MIIet'To (surface: Graphics) I I .,.,. ... *' .... .,. nents. It doesn't know I I ~ ~ whether these subcompo• I I ,.,. ... ' ~il- I Picture nents are other Composites I ,-~--~"' ...._ I ~ Composite ',.. , , -Image: Image or are Leaves. I ... ____ <, - I '~~ +f8lldei'To (surtace:Graphlcs) Leaf: A Component that I ' Leaf I ' ' stands alone; it cannot ' ' II foreach( subelement In container) leat'' SlatlcTextEiement contain anything. subelement.render( surface ); '1 -text: String +f8lldei'To (surface: Graphics) Isuper. prepare( surface ); - II draw the text ~ --

What Problem Does It Solve? X It's not always meaningful or appropriate for every Composite or Leaf to implement Often data structures can be organized into every method of the Component. It's an hierarchies in which everything in the hier• awkward runtime error if an unimple• archy has a common subset of similar proper• mentable method throws an exception. ties. For example, directories are files that can contain other files; a file can be atomic (a simple file not containing anything) or a Often Confused With subdirectory (a file that holds references to Chain of Responsibility: Chain of Responsi• other files, including subdirectories). bility is also implemented using a runtime Composite lets you create these sort of hierarchy of objects, but the point of Chain of containment hierarchies in such a way that a Responsibility is to catch messages in appro• given container doesn't need to know whether priate places. its contents are atomic or composite objects. Decorator: Decorator also uses a containment They both implement the same interface, so strategy, but Decorators add or modify func• can be treated identically. tionality of a single containee. The point of Composite is to make it easier to manipulate Pros (tt) and Cons (•) a set of contained objects. t/ The container is simple to implement because it treats all contents uniformly. See Also t/ It's easy to add new Component classes, Chain of Responsibility, Decorator, Flyweight just derive another class from the Component class (or interface). a The Component tends to specify an unsatis• factory least -common-denominator inter• face. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 367

Implementation Notes and Example Element, is an abstract class that defines abstract class Element operations common to all Element objects (for private Rectangle position; example, the Element's relative position on the public Element(Rectangle position) form). I've avoided making this information { this.position = position; public (thereby damaging the integrity of the } object) by providing a prepare () method that protected void prepare (Graphics surface) modifies the coordinate system of the Graphics { I I modify the surface's coordinate object so that the current object can render itself I I system so that (o,o) is at the in the upper-left comer of the surface. This way I I current Element's position. a getPosition() method is unnecessary, and the resulting class system is more robust. public abstract void renderTo(Graphics surface); The Form class has the role of Composite in the pattern. It's an Element that holds other class Form extends Element Elements, some of which may be Forms and private Collection subelements some of may might be StaticText. The point = new Array list(); is that the Form class's render () method doesn't public Form( Rectangle position ) know or care about the actual type of the sub• { super(position); element. The subelements may be Elements, } or they may be sub-Forms. All subelements public void add(Element subelement) are rendered identically (by passing them { subelements.add( subelement ) ; } render() messages). public void renderTo(Graphics surface) The StaticText class is a Leaf. It is an { prepare(surface); Element that doesn't contain other Elements Iterator i = subelements. iterator(); and thus forms a leaf on the runtime-hierarchy while( i. hasNext() ) tree. It has to know how to render itself, of ( (Element)i. next()) .render( surface); course. Here, it just delegates to the Surface object. class StaticText extends Element private String text; public StaticText(Rectangle position, String text) super(position); this. text = text;

public void renderTo(Graphics surface) { prepare(surface); surface. drawText(text);

Usage Dialog box = new Dialog(); A Dialog is a Composite that can hold Leaves box.add( new Label("Lots of information") ); (such as Label) and other Composites (such as Panel). This example also nicely demonstrates Panel subpanel = new Panel(); the affinity between Composite and Bridge, subpanel. add( new Label("Description") ) ; since AWf is also a bridge. (A DialogFrame, for subpanel.add( new TextField() ); example, is simultaneously a Composite in box.add( subpanel ); Composite and an Abstraction in Bridge.

Another good example of Composite is the new JDOM classes (http:/ /www.jdom.org). An XML document is a list of Elements. 368 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Decorator Attach new responsibilities to (or modify the behavior of) an object at runtime. Decorators can simplify class hierarchies by replacing subclassing with containment.

Component: An interface for objects jaw.utii.Ust •ltrltlrfacB• k1. that can have responsibilities added to ~ ------,I them (or have behavior modified) at +add( item: Object): boolean mponent +remove( Item: Object): boolean s~ I runtime. +size( Item: Object): i"t ...... "";,.------.... , I I II... ~ Decomtor 1 Concrete Component: An object to ,.>-- ___ ""'\..-." I I which additional responsibilities or new ; ,..; '\ I A r·~" ,. I behavior is attached. (ConcrEllo) _. .. Concrete \ i ... I Oecorntor ~ " Component , Decorator: Wraps a Component and Blot:klngUst java.utii.UnkedUst defines an interface that conforms to +add( item: Object ): boolean +add( item: Object): boolean the Component's interface but behaves +remove( item: Object): boolean +remove( ~em: Object): boolean +SIZe( ~em: Object): lot +size( ~em: Objecl ): in! differently. // ... fl ... Concrete Decorator: Extends the Deco• ' rator to define the additional behavior. 11 BlockingUst were an interface, II would be the "Decorator" and itis implementers would be the "Concrete Decorators." In this example, it serves both roles.

What Problem Does It Solve? Pros (~) and Cons (•) Using derivation hierarchies to add features ~ The size and complexity of the class hierarchy is not a great idea. Consider an input stream. is considerably reduced. To add buffering, you'd derive a class that • A feature introduced in a Decorator (such as overrode the input() method to do buffering pushback) is at best hard (or even dangerous) (doubling the number of classes). To add push• to access if the decorator is itself decorated. back, you'd have to derive from both classes, The system is sensitive to the order in which providing buffered and nonbuffered versions Decorators are applied. Java's Pushback!nput• of input () that pushed characters back. In fact, Stream works well at the outermost layer, every feature that you add through subclassing but a PushbackinputStream wrapped with a will require you to double the size of the class BufferedinputStream doesn't work. (It doesn't hierarchy. Decorator, on the other hand, is push back into the buffer.) linear. To add a feature, you add exactly one Decorator class, no matter what the size of the original hierarchy. Often Confused With Decorator also nicely solves the problem Adapter: Changes an interface; Decorator of runtime configuration. Sometimes, you don't changes behavior. know exactly how an object should behave until Chain of Responsibility: Passes messages to runtime. Behavior may be specified in a config• the most appropriate handler. In Decorator, uration file, for example. Decorator allows you messages are handled by the outermost to assemble (at runtime) a composite object Concrete Decorator. that contains exactly the mix of capabilities you need without having to know which of these Composite: Decorators add responsibilities. capabilities will be needed when you write Composites never do. the code. Decorator helps you break up large See Also complex operations into simple Strategy operations. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 369

Implementation Notes and Example Think fish. Bigger fish are Decorators that import java.util.*; implement the same interfaces as the smallest fish (the Component). If a smaller fish has I* I would prefer for this class to be a Linkedlist, swallowed a hook and line, talk to it by yanking * but LinkedList is not an interface, and the string. * useful methods like addFirst() and removeFirst() Blocking list is a ~ * are not defined in an interface. Decorator that modifies the ~ • a *I behavior of any List imple- public class BlockingList implements List mentation so that a thread { private final List component; that tries to remove something from an empty list will (be suspended) until some other public BlockingList( List component ) thread adds something to the list-a common { this.component = component; interthread communication architecture. Use a } Blocking list to add this behavior to any class private boolean noLongerEmpty() of objects that implement the List interface. { try Create a blocking list like this: { while( component.size() == 0 ) List blockingList = wait(); new BlockingList( return true; new Linkedlist() ); } Many methods (such as size() and catch( InterruptedException e ) contains()) behave exactly as they do in the { return false; } List, so they are implemented as simple pass• through methods. Other methods (such as add () and remove ()) implement different synchronized public boolean add(Object o) behavior, so must be implemented at length { boolean toReturn = component.add(o); in the Concrete Decorator. notifyAll(); The behavior of every method in the return toReturn; blocking version at left has changed, however: Everything is now synchronized. If only a hand• synchronized public boolean remove(Object o) ful of methods change behavior (or a Decorator { if( noLongerEmpty() ) just adds a method), simplify implementation return component. remove( o); with an abstract Decorator class that does return false; nothing but define simple pass-through methods to the contained object. Extend the synchronized public int size() abstract class to form a Concrete Decorator, { return component.size(); overriding those methods whose behavior } changes. Other Decorators may add other features. I* Syncrhonized versions of all other methods of A Lazylist may add a close() method that * the List interface are implemented here ... allows subsequent removals from the list but *I disallows additions, for example.

Usage )Component widget = new JtextArea(80,20o); Combines Decorator and Composite: Composite widget = new JScrollPane(widget); because everything's a JComponent; Decorator Jframe frame = new JFrame(); because each successive layer adds functionality Frame.getContentPane().add( widget ); (and changes appearance).

InputStream in= new FileinputStream("x.txt"); The data source is wrapped by a Decorator that in =new BufferedinputStream( in ); adds buffering, which is in turn wrapped by a in = new PushBackinputStream( in ); decorator that supports pushback. Could add decompression, and so on, with additional decorators (GzipinputStream, and so on). 370 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Facade Provide a single interface through which all the classes in a complex subsystem are manipulated. Facade allows you to treat a complex subsystem as if it were a single course-grained object with a simple easy-to-use interface.

Facade: Provides a simple interface to a complex subsystem. Subsystem Classes: Classes that comprise one or more complex subsystems.

What Problem Does It Solve? Pros (tl) and Cons (x) Facade simplifies complex code, making it easier t/ Coupling relationships between subsystems to use poorly designed, overcomplex subsystems. are weakened, improving maintenance and Subsystems, especially older ones, are flexibility. masses ofspaghetti code. When two subsystems X It's still possible for programmers to ignore must interact, they often make calls directly into the Facade and use subsystem classes each other, and these myriad tendrils of connec• directly. tivity are a maintenance nightmare. The sub• systems become very delicate since making seemingly insignificant changes in a single Often Confused With subsystem can affect the entire program. Facade Bridge: Both Facade and Bridge help mainte• addresses the problem by forcing programmers nance by isolating subsystems from each to use a subsystem indirectly through a well• other. Facade simplifies access to, but does defined single point of access, thereby shielding not hide, a subsystem. Bridge completely the programmers from the complexity of the isolates you from the subsystem--you don't code on the other side of the facade. know that the subsystem exists if you use Facade improves the independence of the Bridge. You can use a Facade is to simplify subsystems, making it easy to change--or even access to a bridge. (For example, a Company replace-them without impacting outside code. class could act as a facade to the JDBC Bridge. Facade also provides a manageable way to You'd say Company .getEmployee() and the migrate legacy code to a more object-oriented Facade takes care of the complex series of JDBC structure. Start by breaking up the existing code calls needed to create the Employee object.) into a small number of independent subsys• Mediator: A Facade's communication with a tems, modeled as very heavyweight objects subsystem is unidirectional, or at least simple. with well-defined, simple interfaces. Eliminate Your program sends a message to the Facade, all "end runs" around these interfaces. Then which causes it to send several messages to a systematically replace each subsystem. This subsystem. The subsystem does not talk to, or evolutionary approach significantly reduces even know about, the Facade object. Mediators the risk inherent in an all-at-once rewrite. have complex bidirectional conversations with Facade hides badlydone, overly complex their Colleagues. legacy code. Facade lets you treat an entire legacy system as if it were a single, coarse-grained See Also object. Bridge, Mediator, Observer APPENDIX A DESIGN-PATTERN QUICK REFERENCE 371

Implementation Notes and Example The problem with providing a full-blown class XMLStorage example of a Facade is that there's entirely too { public store(URL out, Object toStore) much code to represent in 40 or so lines-that's { /* Code goes here that uses the the whole point of the pattern. * introspection in the System I'm imagining that the storage method * class to get the class name and the uses Java's introspection APis to analyze the * values of all the public fields in document and discover the fields to save. (It * the class. The name and the values of could just save everything that's public, or it * those fields are then used to build a could look for JavaBean-style get/set methods.) * JDOM tree, which is passed to an I would use the JDOM XML APis to build a tree * "outputter" to send an XML representation of an XML output file and then * representation of the tree to the * OutputStream. send the tree to a JDOM "outputter" class that *I would write the appropriate XML to a file. The loading function reverses this process. By using the facade, you isolate yourself from all the public Object load(URL in); mechanics of introspection, XML parsing, and { /* Code goes here that creates a JDOM. * JDOM SaxBuilder for the InputStream, Messaging is one way; there is no complex * uses it to build a JDOM, instantiates back-and-forth interaction between the * a class named in the XML file, XMLStorage facade and the subsystems that it * then initializes that class using * one of the constructors or a series uses. The Facade object simply builds a tree * of get/set methods. and then outputs the tree. *I We have a facade within a facade here. The SAXBuilder class itself comprises a facade that isolates you from the mechanics of the SAX-parser subsystem. The program can access the JDOM, XML, and Introspection APis directly. Ease of mainte• nance is compromised if you do so and any of these subsystems change. You could avoid this problem by putting the subsystems in an inac• cessible package (such as the com.sun.xxx packages in Java). A Singleton can then be used to get a Facade, through which all access occurs.

Usage SomeString.matches("'[a-zA-Z]{1,3}$"); String acts as a Facade for the regular-expression• matching package, isolating the user from things such as Pattern objects.

Sockets= new Socket("holub.com",7); These two lines hide several pages of C code and InputStream in = s.getinputStream(); all the enormous complexity needed to get a socket to work in a cross-platform way.

AppletContext a = getAppletContext(); AppletContext is a Facade for the browser a.showDocument("http://'iMW.holub.com/index.html") subsystem. Note that this architecture prohibits "end runs" around the facade because subsystem classes are accessible only through the Facade. You can't get at them directly. 372 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Flyweight To minimize memory usage, make objects smaller by using extrinsic state (for example, putting state information into a container or computing it on each access) and sharing (using multiple references to single objects rather than multiple copies of objects).

Flyweight: Defines an interface for messages that use extrinsic state. XMLEJement < name:String Attributes Concrete Flyweight: Implements flyw•l~t •. -- - . - ' +«Slati<;>,...ate (name: String) :XMLEiement ~W~f!)hi - ..{' Fl)'~~ght ) Flyweight with methods that compute + opentllon (J>arent XML_EiemenQ .. fattof)l ".... ~ .. '"J - - - state information or get it from an I I ' ' I ' ' external source (extrinsic state). ' / Con«ora The create() ~ fiyi'JOiglrt method serves as Unstarod cache Not (:otJarentXML...Eiement] 1 manages flyweights. Supplies an existing Concrete Flyweight if one exists; otherwise creates one.

What Problem Does It Solve? Pros (.t) and Cons (•) An object is defined by what it does, not how it tl' Some programs simply cannot be written in an does it. Objects are defined by their methods; object-oriented way without using Flyweight. state information can be inside or outside the tl' When you use flyweight pools, you can deter• object. mine equality using Java's == operator. Sometimes, programs with large numbers of objects require more memory for those X If extrinsic state is stored in a container, objects than is available. In a document editor, then you must access the object through the every character of a naive implementation container. If extrinsic state is computed (for might hold its value, font, color, size, encoding, example, goes to a database every time a position on the page, and so on. This informa• particular attribute is used), then access is slow. tion, duplicated in most characters, can be X Flyweights add complexity to the code, moved to a containing paragraph. If characters impacting maintenance and increasing take up more space than references, keep code size. multiple references to a single "character" object rather than many identical characters. Often Confused With A naive implementation of the Game of Life "cell" may carry a Boolean "is-alive" state Composite: Flyweights are often combined with and references to eight neighbors. A small Composite. Both Leaf and Component nodes 1024xl024 grid requires about 40MB just to can export extrinsic state to their containers. hold the cells. In a Flyweight version, the cell's container knows who the cell's neighbors are See Also to the cell. The and passes that information Composite, Prototype, Singleton cell needs to remember its is-alive state only. By making the neighbor references extrinsic, you reduce the memory requirement for the grid to a single megabyte. In a "flyweight pool," all objects with the same state are represented by a single object. You request objects from the pool, which returns an existing object if possible; other• wise, the pool creates a new object. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 373

Implementation Notes and Example XMLElement is a Flyweight that represents Document (effectively a abstract class XMLElement an Element in an XML { static Map cache = new HashMap(); node in a tree). The element is identified only public static by name, though a more realistic implementa• XMLElement create(String name) tion would identify it both by name and attri• { name = name.intern(); bute values. XMLElement exists = Sharing is used to guarantee that only one (XMLElement) (cache. get (name)); instance of a given element exists. (You could if( exists == null ) argue reasonably that XMLElement is a Singleton; { exists = that is, sharing is implemented using Singleton.) new ConcreteXMLElement(name); The private constructor (and the fact that it's cache.put(name,exists); abstract) force users to use create() rather return exists; than new XMLElement(). The create() method } keeps a cache ofXMLElement objects, keyed by private XMLElement(){} name. If an object with the requested name exists, it is just returned. The create () method abstract void operation( XMLElement parent ); adds an element to the cache only if an element with that name does not already exist. If the private static class ConcreteXMLElement Element doesn't need to know its own name, extends XMLElement its name field can be eliminated to save space. private String name; ConcreteXMLElement(String name) Don't be confused by the fact that { this.name = name.intern(); XMLElement fills two roles in the pattern: } Flyweight Factory and Flyweight. Putting void operation(XMLElement parent) the abstract methods of XMLElement into an { I I ... interface to separating them from the "factory" } functionality makes sense in many situations. public int hashCode() Here, it just adds an unnecessary class. { return name.hashCode(); The intern() method of the String class } enforces sharing in a similar way (see "Usage"). public boolean equals( Object o ) XMLElement also has one extrinsic { return name == ((ConcreteXMLElement)o).name ; attribute: its parent. A heavyweight implemen• tation may keep a parent reference as a field, but here the parent reference is passed as an argument to operation(). This organization saves space, but means that operations on elements that need to know their parent must be started at the root node so that the parent reference can be passed down to them.

Usage JPanel p = new JPanel(); The border size is extrinsic-it's fetched at p.setBorder( runtime from the Component that it borders. BorderFactory.createEmptyBorder(S,S,S,S) ); The Border Factory makes sure that two borders with the same internal state don't exist (when you ask for the second one, you get back a reference to the first one).

StringBuffer b = new StringBuffer(); If an existing String literal has the same value //... assemble string here. as the assembled StringBuffer, then use the Strings= b.toString().intern(); existing literal; otherwise, add the new value to the JVM's internal table of String literals and use the new one. 374 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Proxy Access an object through a "surrogate or placeholder" object.

Proxy: Maintains a reference, and controls access, to the Employee .....,.hoursWorke!l_., Timesheel •abslracl•

~ -ld : long Real Subject. Implements the Subject~ +•sialic- create( id: long ): Timesheet -wage Money ,... + computeSalary(wage: Money): Money same interface as the Real +PriniPaycheckO , Subject so it can be used in , ~ , .. ~ place of the Real Subject. 1 (client) , , ., .. _l 'l , Subject: An interface imple• l , r Timesheet Proxy " J mented by both the Proxy and ..... -.J."":\ , ,.____ " ...... Prox:t,. l +eomputeSalary(wage: Money): Money the Real Subject; allows them J to be used interchangeably. r~ Proxy ,. ;: ~'' . - - - -- • - _ reaiTomesheet TimesheelReal -- -...... _.... _ Real Subject: The real object +eompuleSalary(wage: Money): Money that the Proxy represents. Real Subject--- -

What Problem Does It Solve? Pros (V') and Cons (x) A virtual proxy creates expensive objects on tl' Proxies hide many optimizations from their demand. For example, database access may users, simplifying the code considerably. be deferred by a proxy until the data is actually X Once the real object has been created, used. A large image may be fetched across the access through the proxy adds overhead. network in the background while the user of The whole point of the pattern is to be able the image thinks it's already there. This process to treat the proxy as if it were the real object, is often called lazy instantiation. Vutual proxies so a method such as getRealObject() are also useful in implementing a copy-on• violates the spirit of the pattern. write strategy. When you request a copy of an object, you get back a proxy that simply X You may need to use many remote proxies references the original object. Only when to talk to a large subsystem. It's better to you modify the so-called copy does the proxy create a single remote proxy for a Facade actually copy the state from the original object than it is to create proxies for every class in into itself. the subsystem. A remote proxy is a client-side representa• tion of a server-side object. The proxy relays Often Confused With requests across the network to be handled by Decorator: A protection proxy in particular a sever-side object. CORBA and RMI stubs could be looked at as a Decorator. There's no are proxies for server-side skeleton objects. difference in structure, but the intent is A protection proxy controls access to different-Decorator allows undecorated certain methods of a second object that imple• objects to be accessed indiscriminately. ments the same interface. The proxy method may be passed an authentication token and throw an exception if the token didn't authorize See Also the requested operation. For example: the Decorator, Flyweight Collection implementation returned from Collections. unmodifiableCollection( ... ) is a protection proxy. A smart reference automatically handles annoying background tasks such as deletion. Java's WeakReference is an example. APPENDIX. A DESIGN-PATTERN QUICK REFERENCE 375

Implementation Notes and Example Assume that hourly wage is used heavily class Employee enough to justify a database access when the { private long id; object is created but that the total hours worked private Money wage; I I hourly wage is used only rarely and the Timesheet is needed private Timesheet hoursWorked; by only a few methods. public Employee(long id) I've made the employee identifier a long to { this.id = id; simplify the example. In real code, it would be hoursWorked = Timesheet.create(id); an instance of class Identity. wage = Database.getHourlyWage(id); You could reasonably argue that that the void printPaycheck() Employee should just use for the { Money weekl yWage = Timesheet and dispense with the Proxy object, hours Worked. computeSalary( wage); but the more that Timesheet was used, the less I I •.. weight this argument would hold. I've made Timesheet an abstract class rather than an interface so that I can use it as a factory; abstract class Timesheet otherwise, I'd need a separate TimesheetFactory I I .•. public static Timesheet create(long id) class. { return ( dataAlreadyinMemory ) Accessor methods (get and set functions) ? lookup(id) are evil because they expose implementation : new Proxy(id); detail and impact maintenance. Though it's tempting to use them in this pattern, you'll public abstract Money computeSalary(Money wage); note that no getSalary() or getHoursWorked() I I------method is needed because of the way I've private static class Proxy extends Timesheet { Timesheet realTimesheet = null; structured the messaging system. Don't ask for long id; information you need to do the work; ask the Proxy(long id){this.id = id;} object that has the information to do the work public Money computeSalary(Money wage) for you. One exception to the get/set-is-evil { if( realTimesheet == null ) rule is Database. get Hour 1 yWage ().A database realTimesheet = new Real(id); is fundamentally non-object-oriented; it's just return realTimesheet. a bag of data with no operations at all. Conse• computeSalary(wage); quently, it must be accessed procedurally. If the Timesheet. Proxy threw away the I I------data after computing the salary, it would be a private static class Real extends Timesheet Flyweight, not a Proxy. { Real(long employeeid) { I I load data from the database. } public Money computeSalary(Money wage) { I I Compute weekly salary. return null;

Usage

public void paint(Graphics g) The object returned from getimage() is a { Image img=Toolkit.getDefaulToolkit().getimage( proxy for the real image, which is loaded new URL("http://www.holub.com/image.jpg")); on a background thread. (getrmage() is g.drawimage(img, .•. ); asynchronous; it returns immediately, before completing the requested work.) You can use the image as if all bits had been loaded, even when they haven't. 376 APPENDIX. A DESIGN-PATTERN QUICK REFERENCE APPENDIX A DESIGN-PATTERN QUICK REFERENCE 3n

Behavioral Patterns The behavioral patterns concern themselves with the runtime behavior of the program. I think of them as dynamic-model patterns. They define the roles that objects take on and the way that these objects interact with each other. For example, Chain of Responsibly defines the way that a set of objects routes messages to each other at runtime (so that the object best suited to field a message actually handles the message). All these objects are instances of the same class (or at least imple• ment the same interface), so there's not much in the way of structure in Chain of Responsibility. It's the dynamic behavior of the objects that are important. 378 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Chain of Responsibility A set of objects relay a message from one to another along a well-defined route, giving more than one object a chance to handle the message. The object that's best suited to field a given message actually does the handling. It's possible for more than one object on the route to act on the message.

Handler: Defines -handling Parser.O lspatcher .I Ptlrwr •lnllllfllce• I interface and optional successor +addParser( Parser p ) ~Routs messages to> I+parse( input String): boo/8an I link. +Parse( input String): boolean ,-' "' Handl•r Concrete Handler: Handles , ; 1:::. I (Dispatcher) , , .-' I request or, by doing nothing, \ I \ ...... , ,.-"' I __ ... __ Concrete causes event to be forwarded to , I ChaJnot Handler I "' ' }------XMLParse! successor. ', ,..Responsibility _____ ,. "' +parse( input String ): boolean 1 Dispatcher (not a Gang-of-Four I Client 1 --,;:. I 0 I I role): Routes the event to each Client handler in turn. Not required if 1- ______~ --"1======.=:==c7sv::;::Pa:;:rse:=r=:=:='==.:=:=f .______. •create• +parse( input: String ): boolean Handlers are organized as a linked list.

What Problem Does It Solve? tl' The coupling between objects in the program is loosened if an implementation permits Makes it easy to add new customized message Handler classes not to know about each other. handling at runtime. An "event" or a message can be passed to a sequence of handlers, and X In Wmdows, when a mouse moves one pixel, the one that is best suited to handle the the WM_ MOUSEMOVE message is first received by message actually does so. the window that has focus, perhaps a text In Microsoft Wmdows, every button, frame, control. This control doesn't know how to and so on, is a Window object, arranged using it, so it passes the message to the . Events (messages created by containing panel, which passes it to the MDI a user action) are passed to the window that has child window, which passes it to the main the focus (typically a button or other widget), frame, which passes it to the menu bar, and if that window can't handle the message, it which passes it to each menu item. None of passes it to its parent window (typically a frame these objects can handle the message, so it's window or a menu bar). The Wmdow that discarded. This is a lot of work to do nothing. understands the message actually handles it. X Many reifications force you to use imple• Servlet "filters" are another use of the mentation inheritance to specify a message pattern. An incoming HTTP packet is passed handler, inappropriately forcing strong through a sequence of filters, which can process coupling between Handler classes and the packet directly or pass the packet to the next introducing fragile base classes into filter in the chain (or both). the model. Also consider a system of subclasses in which each constructor parses from a String the information of interest to it, and then it Often Confused With passes the String to the superclass constructor. Composite: Composite specifies one way that a Chain of Responsibility may be ordered Pros (V') and Cons (x) (from contained object to container, recur• sively). This is not the only way to order the tl' The dynamic behavior of the program can chain, however. be easily changed at runtime by adding new handlers to the chain or changing the ordering of handlers. See Also Composite, Observer APPENDIX A DESIGN-PATTERN QUICK REFERENCE 379

Implementation Notes and Example Create a parser for a particular input interface Parser format by implementing the Parser interface. { boolean parse( String input ); The two versions at left (XMLParser and CVSParser) static class Dispatcher handle XML and comma-separated-value { private List parsers = new Linkedlist(); formats. The parse( ... ) method examines the public void addParser( Parser p ) { parsers.add( p ); input, and if it recognizes the input format, it } parsers it and returns true; otherwise, parse( ... ) public boolean parse( String input ) returns false. The Parser. Dispatcher() object { for( Iterator i=parsers.Iterator(); just keeps a list of Parser implementations and i.hasNext(); ) { Parser p = (Parser)( i.next() ); passes the messages to them one at a time until if( p.parse( input ) ) it finds one that can handle the input string. return true; Parse an input string like this: } return false; Parser.Dispatcher dispatcher = new Parser.Dispatcher(); dispatcher.addParser( new XMLParser() ); } dispatcher.addParser( new CSVParser() ); class XMLParser implements Parser I 1... { private static Pattern scanner = if( !dispatcher.parse( inputString ) ) Pattern.compile("A\\s*<"); System.err. println( "Can't parse input"); public boolean parse( String input ) { Matcher regex = scanner.matcher(input); The Gang-of-Four reification does not if( !regex.lookingAt() ) return false; have an object in the Dispatcher role. (The II Parse the XML file here. term dispatcher is mine.) In the Gang-of-Four return true; reification, the Concrete Handler objects form a simple linked list, the input is passed to the } class CSVParser implements Parser first handler in the list, and any handler that { private static Pattern scanner = can't process the input just delegates to the Pattern.compile( next handler in the list. "([a-zA-Z0-9]*,)*[a-zA-Z0-9]+"); public boolean parse( String input ) { Matcher regex = scanner.matcher(input); if( !regex.matches() ) return false; II Parse a comma-separated-value string return true;

}

Usage public class MyFilter Each object on the route typically keeps a implements javax.servlet.Filter reference to its successor, but the pattern II ... doesn't mandate this organization. For example, public void doFilter(ServletRequest req, a centralized dispatcher may pass a message to ServletResponse rsp, several objects in turn. What's important is that FilterChain chain) the object, not the dispatcher, decides whether II ... to handle the message. Servlet filters are chain.doFilter(request, response ); dispatched by the web server. Tomcat, for II ... example, uses information that you put into a configuration file to determine the dispatch sequence. class MyWindow extends Component Chain-of-Command GUI handling was { public boolean keyDown(Event e, int key) abandoned as unworkable in version 1.1 of]ava { II code to handle key press goes here. (in favor of the better ). This } deprecated method is a holdover from then. 380 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Command Encapsulate a request or unit of work into an object. Command provides a more capable alternative to a function pointer because the object can hold state information, can be queued or logged, and so forth.

Command: Defmes an interface for TextEditor -undoStack Action executing an operation or set of opera• 0 .. • •interface• -HieleteCharacter (c: char) tions. +lnserteharacter (c: char) +do/10 Concrete Command: Implements +Process (command: Action) +Undo// 0 +i'edOQ -redoStack the Command interface to perform the -HJndo 0 o.; .... Conu11and operation. 1YJ>ically acts as an interme• Invoker '...... _,,. diary to a Receiver object. ' , ~ ,.,...... ---""'"' ~--, Concrete 1 (Almmand ) I I Invoker: Asks the command to carry ' .... (Almm and I ~ - T - ~ ~ ~ ,-----..,-...... L.-, out a request. 1 lnsertAction I It -current Rece1ver ,' I Receiver: Knows how to carry out the r-'L.....;___;,_C_urs_o_r___;_;,;,:---i -where -inserted: char I I request. This functionality is often built -HioltO I in to the Command object itself. +eharacterAtO: char -HJndolt 0 I +Clone O: Object I -HieleteCharacterAt O: void +moveRight O: void -where DeleteActlon +moveTo Q: void -deleted: char +dOII0 +UndoltQ

What Problem Does It Solve? encapsulate both "undo" and "redo" opera• tions and the state information necessary to You can't have a function pointer in an 00 perform these operations. system simply because you have no functions, Command also nicely solves "callback" only objects and messages. Instead of passing problems in multithreaded systems. A "client" a pointer to a function that does work, pass a thread creates a Command object that performs reference to an object that knows how to do some operation and then notifies that client that work. when the operation completes. The client then A Command object is effectively a trans• gives the Command object to a second thread action encapsulated in an object. Command on which the operation is actually performed. objects can be stored for later execution, can be stored as-is to have a transaction record, can be sent to other objects for execution, and Pros (v) and Cons (ac) soon. V' Command decouples operations from the Command is useful for tasks such as "undo" object that actually performs the operation. operations. It's not possible to undo an opera• tion simply by rolling the program back to a previous state; the program may have had an Often Confused With effect on the outside world while transitioning Strategy: The invoker of a Command doesn't from the earlier state to the current one. know what the Command object will do. A Command gives you a mechanism for actively Strategy object encapsulates a method for rolling back state by actively reversing side doing a specific task for the invoker. effects such as database updates. By encapsulating the work in an object, See Also you can also define several methods, and even state information, that work in concert to do Memento, Strategy the work. For example, a single object can APPENDIX A DESIGN-PATTERN QUICK REFERENCE 381

Implementation Notes and Example public Inserter(char newCharacter) { inserted = newCharacter; abstract class Cursor extends Cloneable } { public Object clone(); public void dolt() public char characterAt(); { current.moveTo( where ); public void deleteCharacterAt(); current. public void insertCharacterAt( insertCharacterAt(inserted); char newCharacter); current.moveRight(); public void moveTo(Cursor newPosition); public void moveRight(); public void undoit() II ... { current.moveTo( where ); } current.deleteCharacterAt(); class TextEditor { private Cursor current = new Cursor(); private Linkedlist undoStack = private class Deleter implements Action new Linkedlist(); { Cursor where = (Cursor) current.clone(); private Linkedlist redoStack = char deleted; new Linkedlist(); public void dolt() public void insertCharacter(char c) { current.moveTo( where ); { process( new Inserter(c) ); deleted = current.characterAt(); } current.deleteCharacterAt(); public void deleteCharacter() } { process( new Deleter() ); public void undoit() } { current.moveTo( where ); private void process( Action command current.insertCharacterAt( deleted); { command.doit(); current.moveRight(); undoStack.addFirst(command); } } public void undo() I I ... { Action action = (Action) undoStack.removeFirst(); action.undoit(); Most of the work is done by the Cursor, redoStack.addFirst( action ); which reifies Iterator. The TextEditor is driven } public void redo() by a Client class (not shown) that interprets { Action action = user input and tells the editor to perform tasks (Action) redoStack.removeFirst(); such as inserting or deleting characters. The action.doit(); TextEdi tor performs these request by creating undoStack.addFirst( action ); Command objects that implement the Action interface. Each Action can both do something private interface Action and also undo whatever it did. The editor tells { void dolt (); void undoit(); the Action to do whatever it does and then stacks the object. When asked to undo some• private class Inserter implements Action thing, the editor pops the Action off the undo { Cursor where = (Cursor) current.clone(); stack, asks it to undo whatever it did, and then char inserted; puts it on a redo stack. Redo works in a similar way, but in reverse.

Usage new Thread() Thread is passed a Runnable Command { public void run(){ 1* ..• *1 object that defines what to do on the }.start(); thread. java.util.Timer t =new java.util.Timer(); Print hello world one second from now. t.schedule( new java.util.TimerTask() The TimerTask is a Command object. { public void run() Several TimerTask objects may be queued {System.out.println("hello world");} for future execution. }, 1000); 382 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Interpreter Implement an for a language, first defining a formal grammar for that language and then implementing that grammar with a hierarchy of classes (one subclass per production or non terminal).

Abstract Expression: Defines an "interpret" operation (or operations). ANDLogic k------Loglc.Values ...,valuate O +assign(l k1 { - I Variable 1£.------~.., operation for a terminal symbol [...,..lualli) [""'va luateQ ~ ~Context J : ~ (which appears in the input). 1 -operands I ' ' ~ TermiMI I I I , .,...... bpression I I " I I I_-' ORLogic Nonterminal Expression: Implements k:' ...... 1 I Nont~lltal ...... , an operation for a nonterminal I .I .evaluateO Expres.sH)I'l -~---- .. I I ------·( o1terpreter ) symbol (a grammatical rule). I ,,.------I AIJs1ract <>:pression ., - Context: Global information (for L------~ example, variable values).

What Problem Does It Solve? the JVM? Your users write scripts in Java and provide you with a string holding the class You sometimes cannot define all the required name. Use Java's introspection APis to load behavior of a program when you write it. For and execute the user-supplied code, or, if the example, there's no way for the browser writer to user code implements a well-defined inter• predict the way a site may want a web face, then execute directly. Given the following: page to behave. An interpretive language such as JavaScript can add behavior to the program that public interface UserExtension wasn't contemplated by the author. { void doSomething(); The defines one way } to build an interpreter. You first define a formal instantiate and execute a user object like this: grammar that lists rules (called productions) that describe the syntax of the language. You String name = then implement a class for each production. System.getProperty("user.extension"); These classes share a Context object from which class userMods = Class.forname(name); they get input, store variable values, and so UserExtension userExtentionObject = forth. An interpreter may (or may not) create (UserExtension) userMods.newinstance(); an efficient output processor (such as a state userExtensionObject.doSomething(); machine) that does the actual work. Write your own class loader and/ or security manager to create a sandbox. Pros (V') and Cons (x) Applets demonstrate this technique. Rather X The pattern says nothing about how to create than interpret code (ala JavaScript), you the graph of objects that comprise the inter• provide a class to the browser, which it preter (the Abstract Syntax Tree). Interpreter executes. Applets communicate with the often requires a nontrivial parser to construct browser via the AppletContext Facade. this graph, and often this parser can just do the interpretation. Often Confused With t/ Modifying the grammar is relatively straight• Chain of Responsibility: Chain of Responsibility forward; you just create new classes that is used in interpreter to evaluate the input represent the new productions. sentence. It's Interpreter only when the objects X Interpreter doesn't work well if the grammar implement grammatical rules. has more than a few productions. You need Composite: Interpreter is implemented as a too many classes. Use traditional compiler Composite. tools (such as JYACC, CUP, and so on) or a hand-coded recursive-decent parser for See Also nontrivial languages. Strategy, Visitor X Why provide an interpreter when you have a perfectly good one already in memory: APPENDIX A DESIGN-PATTERN QUICK REFERENCE 383

Implementation Notes and Example Consider the following Boolean-expression interface Logic grammar: { public static class Values e .. - e '&' e { static Map vars = new HashMap(); e 'I' e static void assign( String key, , ! , e boolean value ) '(' e ')' if(key==nuu II key.length() <= o) var '=' e throw new Exception("Logic"); var vars.put(key, value? Boolean.TRUE : Boolean. FALSE); The code at the left comprises an inter• } preter for that grammar. (I haven't shown static boolean lookup( String key ) OR Logic and NOTLogic classes, since they're { Object got = vars.get(key); trivial variants on AND Logic.) Variable values return ((Boolean)got).booleanValue(); are held in the Values Singleton. Create an interpreter for X= (A & B) I ! Cas follows: } boolean evaluate(); Logic term = new ANDLogic( new Variable("A"), new Variable("B") class ANDLogic implements Logic ); { Logic left, right; term = new ORLogic( public ANDLogic(Logic left, Logic right) term, { this.left = left; new NOTLogic( new Variable("C") this.right = right; ) j } term = new AssignmentLogic( public boolean evaluate() { return left.evaluate() new Variable("X"), term ); && right.evaluate(); Assign values in the code (or by reading user input) like this: Logic.Values.assign{"A", true); class ORLogic implements Logic{/* ... */} Logic.Values.assign("B", true); class NOTLogic implements Logic{/* ... */} Logic.Values.assign("C", false); boolean result = term.evaluate(); class AssignmentLogic implements Logic The Interpreter pattern makes no sugges• { Logic left, right; tions as to how you may construct the abstract• public Assignmentlogic(Logic 1, Logic r) syntax tree that represents the expression (the { this.left = 1; this.right = r; tree of Logic objects), but some sort of parser is } implied. public boolean evaluate() Alternatively, you could use Visitor to { boolean r = right.evaluate(); traverse the syntax tree: Visit the notes in depth• Logic.Values.assign(left.toString(),r); first order; code in the visitor object determines return r; what happens as it visits each node. You could traverse once to test internal integrity, traverse } again to optimize the tree, traverse a third time class Variable implements Logic to evaluate the expression, and so on. Separating { private String name; the structure of the abstract syntax tree from the public Variable(String s){name = s;} logic of code generation and optimization can public String toString(){ return name; clean up the code substantially, but the visitor public boolean evaluate() { return Logic.Values.lookup(name); can end up as a quite-large class and will be hard } to maintain as a consequence.

Usage java.util.regex.Pattern p=Pattern.compile{"a*b"); Uses Interpreter internally. (See the source java.util.regex.Matcher m = p.matcher("aaaaab"); code shipped with the JDK.) boolean b = m.matches(); 384 APPENDIX . A DESIGN-PATTERN QUICK REFERENCE

Iterator Access the elements of an aggregate object sequentially without exposing how the aggregation is implemented.

Iterator: Interface for accessing canonymouso IIBrator •lnfllrfllce• ~------and traversing elements . +h&sNertO: boolean .. -..... -. -lhasNext O: boolean +IM.rtO: Object -- ...... , " .. External" 'L ~ ... - ... - .. -mext 0: Object Concrete Iterator: Implements I tarat or ~orator , Contrete +IVIIIOI'IIQ:void ' ,. __ .... ., +m~K~ve O: void ., Iter a! or Iterator and keeps track of current , \ , Roo , , Concrete' position. :i• , , AQgregate \ !!tl , Tree ~ ~~~s Aggregate: Defines an interface for <: r Aggregale , , +il!ratorO: ~orator creating an iterator. (Omit if no I Collection •interlace• 1.,..., __ +tra~~(cllen t : Examiner) ~ r---

What Problem Does It Solve? • The aggregate may store references to its ; memory leaks are possible if you lterators isolate a data set from the means that's discard an iterator without notifying the used to store the set. For example, Java Collec• aggregate. tion and Map classes don't implement a common interface. You can, however, extract an iterator • It's difficult to control the traversal • from a Collection (using iterator()) and from a rithm and retain the generic quality of an Map (using values() .iterator()). Pass the iter• iterator. For example, there's no way to ator to a method for processing, thereby isola - specify a post-order traversal from the iter• ting that method from knowledge of how the ator returned from a Tree Set. This problem objects are stored. extends to most Composite reifications. The set of objects need not be stored inter• • It's difficult to implement lterator in an nally at all-an iterator across a Flyweight may environment that supports simultaneous read objects from disk or even synthesize them. iteration and modification. (If you add an Iterators make it easy to have multiple item to an aggregate while iterations are in simultaneous iterators across an aggregation. progress, should the iterator visit the newly lterators can manipulate the aggregation. added item? What if the list is ordered and The Cursor class in the Command example is an you've already passed the place where the iterator. Java's Listiterator can modify the list. new item is inserted? Should attempts to External or active iterators are controlled by modify the aggregation fail if iterators are the client (for example, Java's Iterator class). active? There are no "correct" answers to Internal or passive iterators are controlled by the these questions.) aggregate object. A tree may have a traverse• PostOrder() method that's passed a Cormrand object that is, in turn, passed each node in the Often Confused With tree. External iterators are often harder to imple• Visitor: Visitor can be implemented with a ment than internal ones. passive iterator. lterators should examine data, not modify it. Visitors are passed from node to Pros (v) and Cons (x) node; lterators are passed the node to visit. t/ Promotes reuse by hiding implementation. See Also • A client may modify the elements of the aggregation, damaging the aggregate (for Composite, Visitor example, change the key in sorted aggregate). APPENDIX A DESIGN-PATTERN QUICK REFERENCE 385

Implementation Notes and Example The previous code implements a simple class Tree implements Collection binary tree. (I've omitted the methods of { private Node root = null; Collection that aren't relevant to Iterator.) The private static class Node iterator() method returns an external iterator { public Node left, right; that implements the java. util. Iterator inter• public Object item; face. Use it like this: public Node( Object item ) Iterator i = t.iterator(); { this.item = item; while( i.hasNext() ) } Iterator iterator() System.out.print(i.next().toString() ); { return new Iterator() You can't use recursive traversal in an { private Node current = root; external iterator because next () must return private Linkedlist stack = after getting each element, and you can't stop new Linkedlist(); the recursion in midstream. My implemena• public Object next() tion uses a stack to remember the next parent { while( current != null ) to visit in the traversal (the same information { stack.addFirst( current ); current = current.left; that would be on the runtime stack in a recur• } sive traversal). You can easily see the extra if( stack.size() != o ) complexity mandated by this approach, but { current = (Node) other nonrecursive traversal algorithms are, if ( stack.removeFirst() ); anything, messier. Object toReturn=current.item; The traverse() method demonstrates an current = current.right; internal iterator. You pass traverse() a Command return toReturn; object that implements the Examiner interface. } 'fraverse does a simple recursive traversal, throw new NoSuchElementException(); passing each node to the Examiner's examine() } method in order. Here's an example: public boolean hasNext() { return !(current==null t.traverse( && stack.size()==O); new Tree.Examiner() } { public void examine(Object o) public void remove(){ 1* .•• *1} { System.out.print(o.toString()); }; } } ) ; public interface Examiner { public void examine( Object o ); As you can see, the code is much simpler, void traverse( Examiner client ) but you lose the flexibility of an external iter• { traverselnorder( root, client ); ator (which you could keep positioned in the } middle of the tree, for example; an internal private void traverseinorder(Node current, iterator doesn't give you the option of not Examiner client ) advancing). if( current == null ) Both iterators access private fields of Tree. return; Think of an external iterator as an extension of traverselnorder(current.left, client); the object that creates it. Private access is okay client.examine (current.item ); if it doesn't expose implementation informa• traverselnorder(current.right, client); } I I ... tion. Nonetheless, iterators are tightly coupled to the aggregate by necessity.

Usage f( Collection c ) Iterators are used heavily in all the Java Collection Iterator i = c.iterator(); classes. while( i.hasNext() ) doSomething( i.next() ); }

String query = "SELECT ID FROM TAB"; A database cursor iterates across rows in a table. ResultSet results = stmt.executeQuery(query); while( results.next() ) String s = results .getString("ID"); 386 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Mediator Define a single object that encapsulates a set of complex operations. Mediator simplifies your code by hiding complexity; it loosens coupling between the objects that use the mediator and the objects the mediator uses.

Mediator: (Often omitted.) r------, Colleague ~.,.. .. -- .. ' .. Defines an interface to Colleagues. I Client ~ ------... Mediator,.._ Concrolll ., ... "" .. ?_ ...... ~ ..... ------... Colleague Concrete Mediator: Implements I ~ o:ediatDJ '' I / rl ·;= I _ ___.l communication between them. *Concrete/ Colleagues: A system of interfaces 1 MetlllltorJ -J ' Jframe I and classes that communicate I SwlngQuery 1..::.. bidirectionally through the medi• l ....,sk(Siring messasge): Siring 1 ... Jllilfleld I ator rather than directly. Note that the client is a Colleague.

What Problem Does It Solve? Often Confused With Mediator makes complex operations simple. Facade: Facade eases simple one-way commu• Too-complex code is damaging to any nication with a subsystem helps isolate the program. Mediator solves this problem by subsystem from the rest of the program. Medi• taking complex code that would otherwise ators encapsulate complex interactions, but appear all over the program and encapsulating communication is bidirectional and they do it into a single object with a simple interface not isolate anything from anything. It's possible, that's used all over the program. Mediators however, for a set of classes to participate hide complex protocols. simultaneously in both patterns. Bridge: Bridge and Mediator both reduce Pros (V') and Cons (x) coupling between subsystems. Bridge defines tl' Mediators improve code organization in a standard (often complicated) interface and many ways: reducing subclassing, decou• then implements it in various ways. Bridges are pling subsystems, and simplifying systems of classes. Mediators are objects that messaging systems and protocols. have simple interfaces but do complex work at runtime. Mediator does promote decoupling, X Complexity can creep into a Mediator over though. If a protocol changes, for example, the time as you customize it for new applica• of that change is typically limited to the tions. You've missed the point if you allow a Mediator itself. Mediator to become too complex. Several Mediators tailored for specific applications can help. Be careful not to add back the See Also complexity you're trying to eliminate. Facade, Bridge X A mediator can turn into a "god" class if you're not careful. A good 00 program is a network of cooperating agents. There is no spider in the middle of the web pulling the strands. Focus your mediators on doing one thing only. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 387

Implementation Notes and Example The previous code lets you ask the user a interface Query simple question. When you make this call: { String ask( String question ) ; Query user= new SwingQuery(); } String answer= user.ask("How are you"); class SwingQuery implemnts Query { public String ask( String question ) { final Object done = new Object(); !§® final Object in it = new Object(); final JFrame frame = new JFrame("Query"); final JTextField answer= new JTextField(); The method displays the small window answer. setPreferredSize ( new Dimension ( 200, 20)); shown previously. You type your answer and hit frame .getContentPane(). set layout( Enter, the window shuts down, and ask( ..• ) new Flow layout() ) ; returns what you typed (in this case, the string frame .getContentPane(). add( answer ) ; "Fine"). Ifyou click theXboxin the upper• frame.getContentPane() .add( right comer of the control, the window shuts new Jlabel(question) ); answer.addActionlistener I I submit down and ask( ... ) returns an empty string. ( new Actionlistener() The details of the code are actually not { public void actionPerformed(ActionEvent e) relevant to the current discussion. The main { synchronized( init ) issue is that the code encapsulates a complex { synchronized( done ) interaction with the GUI subsystem (and would { frame. dispose(); done. notify(); be even more complex if you were working in }}}}); the raw OS rather than Java), but the user exer• frame. addWindowlistener I I cancel cises all this complexity by doing a simple thing. ( new WindowAdapter() The details are all hidden. Moreover, code that { public void windowClosing(WindowEvent e) Query is now considerably simplified, and a { synchronized( init ) uses { synchronized( done ) lot of complicated junk isn't duplicated all over { frame.dispose(); the program. answer. setT ext (""); It would be better if the Concrete Mediator done. notify(); (the SwingQuery) were created by an Abstract }}}}); Factory rather than by invoking new. synchronized( done ) { synchronized( init ) Note that Mediator does not isolate the { frame.pack(); program from the entire Swing subsystem frame. show(); (unlike Bridge). Mediator does not prohibit } other parts of your program from talking try{ done.wait(); } directly to Swing. Also note that the communi• catch( InterruptedException e ){} } cation between the Mediator (Query) and its return answer. getT ext(); colleagues (everything else) is bidirectional, } and that all communication (at least in the } context of asking the user a question) happens through the mediator.

Usage URL home= new URL("http:llwww.holub.com"); The output stream returned from the URLConnection is URLConnection c = home.getConnection(); a Mediator. You just write data to it. It encapsulates // ... the complex interaction needed to establish a OnputStream out = c.getOutput(); connection and implement whatever protocol was c.write( someData ); specified in the original URL. JButton b = new JButton("Hello"); The JButton deals with all the complexity of fielding II .. . mouse clicks, changing the image the user sees when the button should be "down," and so on. JOptionPane.showMessageDialog("Error ... "); Hides the complexity of creating and showing a dialog box. 388 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Memento Encapsulate an object's state in such a way that no external entity can know how the object is struc• tured. An external object (called a caretaker) can store or restore an object's state without violating the integrity of the object.

Originator: Creates a memento that holds a Originator ., < srores state of "snapshot" of its current state. +QetMementoO: Object +restoceFrom( memento: Object) Memento: Stores the internal state of the Origi• • 1 Originator ', nator in a way that does not expose the structure ~I ' ~· ,;----~, of the Originator. Supports a "wide" interface ~ 1 ' Memento 1 used by the originator and a "narrow" interface t Memento~,>- ... ----~:_ used by everyone else. .q / ~ ' .., ... :_arelaker <)__ Caretaker: Stores the mementos but never oper• I Memento ~·memento g) I Caretaker I ates on them.

What Problem Does It Solve? Pros (11} and Cons (x) The ubiquitous get/set (accessor) function is t1 Allows an object's state to be stored exter• evil. Allowing access to internal fields-either nally in such a way that the maintainability directly by making them public or indirectly of the program is not compromised. through an accessor method-flies in the face tl Allows a "caretaker" object to store states of of the basic object-oriented principle of imple• classes that it knows nothing about. mentation hiding. The whole point of an 00 structure is that you can make radical changes X Versioning can be difficult if the memento is to an object's implementation without stored persistently. The Originator must be impacting the code that uses those objects. able to decipher mementos created by An object should not get the data that it needs previous versions of itself. to do work-it should ask the object that has X It's often unclear whether a memento the data to do the work for it (delegation). The should be a "deep" copy of the Originator. only exception to this rule is an accessor that (in other words, should recursively copy not returns an object that opaquely encapsulates just references but the objects that are refer• the data. The point is not to expose implemen• enced as well). Deep copies are expensive tation details. to manufacture. Shallow copies can cause If you use simplistic accessors, even memory leaks, and referenced objects may small changes, such as changing a field's type, change values. impact every part of the program that uses X Caretakers don't know how much state is in that accessor. Programs that use accessors are the memento, so they cannot perform effi• difficult to maintain and simply aren't object cient memory management. oriented. (A program isn't 00 just because it uses classes, derivation, and so on, or is written in Java or C++.) Otten Confused With But what if an external entity needs to Command: Co11111and objects encapsulate opera• remember the state of some object, perhaps tions that are known to the invoker. Mementos to restore that state in an undo operation or encapsulate state-operations are unknown to equivalent? Memento solves this problem by the caretaker. having the original object return a black box, an impenetrable container that the caretaker can store but not manipulate. The object that manufactures the black box does know what's in it, though, so it can use this information at will (to restore state, for example). APPENDIX A DESIGN-PATTERN QUICK REFERENCE 389

Implementation Notes and Example but "against stupidity, even the gods them• class Originator selves contend in vain.") The Caretaker treats { private String state; the Memento as a simple Object. Memento private int more; defines a "narrow" interface (toString()) that doesn't expose structure. A much more private class Memento complicated memento is presented in { private String state = Chapter 3 in the Game-of-Life example. Originator.this.state; One great example of Memento is an private int more =Originator.this.more; "embedded" object in Microsoft's Object public toString() Unking and Embedding (OLE) framework. { return state + ", " + more ; } Consider an Excel spreadsheet that you've embedded as a table in a Word document. When you create the table, Excel is running. public Object getMemento() It negotiates with Word to take over some of its { return new Memento(); UI (Excel adds menus to Word's menu bar and } is in control of the subwindow that holds the table, for example). When you click outside public Object restore(Object o) the table, Excel shuts down and produces a { Memento m = (Memento) o; memento-a blob of bytes that holds its state• state = o.state; and an image that Word displays in place of the more = o.more; original Excel UI. All that Word can do with this image is display it. All that Word can do with the data "blob" is hold onto it. The next time class Caretaker the user wants to edit the table, Word passes Object memento; the blob back to Excel, but Excel has to figure Originator originator; out what to do with it. Since Excel's data repre• public void captureState() sentation is completely hidden from Word, it { memento = originator.getMemento(); can change the representation without } impacting any of the code in Word itself. public void restoreYourself() { originator.restore( memento ); A memento can have a "narrow" interface } that does something such as display its state on a screen or store its state as an XML file. Just make sure that this interface doesn't expose Making Memento private with nothing but any structure to the caretaker. private fields guarantees that unsafe access is "Undo" is hardly ever implementable impossible. (Some idiot may try to circumvent solely with a memento (see "Command"). encapsulation using the introspection APis,

Usage class Originator implements Serializable{ int x; } A byte array is about as black as a box can be. Decorator is ByteArrayOutputStream bytes = new ByteArrayOutputStream(); used here to produce a system ObjectOutputStream out= new ObjectOutputStream( bytes ); of streams that manufacture the memento. This example Originator instance= new Originator(); II create also nicely illustrates a flaw in out.writeObject( instance ); II memento Decorator-that you sometimes byte[] memento = bytes.toByteArray(); have to access an encapsulated decorator to do work. ObjectinputStream in = II restore object new ObjectinputStream( I I from memento new ByteArrayinputStream(memento)); instance= (Originator) in.readObject(); 390 APPENDIX • A DESIGN-PATTERN QUICK REFERENCE

Observer (Publish/Subscribe) When an object changes states, it notifies other objects that have registered their interest at runtime. The notifying object (publisher) sends an event (publication) to all its observers (subscribers).

Subject (The publisher). Notifies ?Collodion Observers that some event has 1 notlfles> o.. • NotllyingColledion occurred. Keeps a subscription -publisher +addSusbscrlber(lislener. Subscriber) ... +adclodtlemtilem: Obfeje

What Problem Does It Solve? Pros (II) and Cons (x) In Chain of Responsibility, a button notifies a II Observer nicely isolates subsystems, since parent of a press event like this: the classes in the subsystems don't need to class Window know anything about each other except that { void buttonPressed() {/* ... */} they implement certain "listener" interfaces. II ... This isolation makes the code much more reusable. • You have no guarantee that a subscriber class Button implements Window won't be notified of an event after the { private Window parent; subscriber cancels its subscription-a side public Button(Window parent) effect of a thread-safe implementation. { this.parent = parent; } (AWf and Swing both have this problem.) public void onMouseClick() • Publication events can propagate alarmingly { parent.buttonPressed(); } when observers are themselves publishers. It's difficult to predict that this will happen. An abstraction-layer (business) object must *C Memory leaks are easily created by "dangling" learn about presses through a Mediator called references to subscribers. (When the only a controller-a Window derivative that overrides reference to an Observer is the one held by a button Pressed() to send a message to the busi• Subject, a dangling Concrete Observer may ness object. The coupling relationships between not be garbage collected.) It's difficult in Java, the controllers, the abstraction layer, and the where there are no "destructor" methods, to presentation (the button) are too tight. Too guarantee that publishers are notified when a much code is affected if anything changes. subscriber becomes irrelevant, and it's easy to The Observer pattern addresses the problem forget to explicitly cancel the subscription. by adding an interface between the publisher of an event (the button) and a subscriber (the busi• Often Confused With ness object that's actually interested in the button press). This interface decouples the publisher and Command: Command objects are very generic. makes it reusable in the sense that it's a stand• Observers are used solely for notification. alone component, with no dependencies on the Strategy: Strategy objects define a strategy for rest of the system. A Subject can notify any class performing some work. Observers do imple• that implements the Observer interface, as ment a notification strategy but, unlike Strategy compared to the earlier example, where a Button objects, are not called from within methods to could notify only a Window. do work. See Also Chain of Responsibility APPENDIX A DESIGN-PATTERN QUICK REFERENCE 391

Implementation Notes and Example The example at left is a Decorator that public final class NotifyingCollection wraps a collection to add a notification feature. implements Collection Objects that are interested in finding out when private final Collection c; the collection is modified register themselves public NotifyingCollection(Collection wrap) with the collection. { c = wrap; } In the following example, I create an private final Collection subscribers "adapter" (in the Java/ AWf sense, this is not = new Linkedlist(); public interface Subscriber the Adapter pattern) that simplifies subscriber { void addeditem ( Object item ); creation. By extending the adapter rather than void removeditem ( Object item ); implementing the interface, I'm saved from } having to implement uninteresting methods. I synchronized public void addSubscriber( then add a subscriber, like so: Subscriber subscriber) { subscribers.add( subscriber ); } class SubscriberAdapter implements synchronized public void removeSubscriber( NotifyingCollection.Subscriber Subscriber subscriber) public void addeditem(Object item){} { subscribers.remove( subscriber ); public void removeditem(Object item){} } private void notify(boolean add, Object o) { Object[] copy; NotifyingCollection c = synchronized(this) new NotifyingCollection(new Linkedlist()); { copy = subscribers.toArray(); c.addSubscriber } ( new SubscriberAdapter() for( int i = o; i < copy.length; ++i ) { public void added( Object item ) { if( add ) { System.out.println("Added " + item); ((Subscriber)copy[i]]).additem(o); } else ((Subscriber)copy[i]).removeitem(o); } } This implemenation of Observer is simplistic-copy is a very inefficient strategy public boolean add(Object o) { notify(true,o); return c.add(o); } for solving the problem of one thread adding or public boolean remove(Object o) removing a subscriber while notifications are { notify(false,o); return c.remove(o); } in progress. A more realistic implementation public boolean addAll(Collection items) was presented in Chapter 3. { Iterator i = items.iterator() Observer encompasses both one-to-many while( i.hasNext() ) and many-to-one implementations. For notify( true, i.next() ); return c.addAll(items); example, one button could notify several } observers when it's pressed, but by the same II pass-through implementations of other token, several buttons could all notify the same II Collection methods go here ... subscriber, which would use some mechanism (perhaps an event object passed as an argu• ment) to determine the publisher. Usage

JButton b = new JButton("Hello"); Print World when the button is pressed. b.addActionlistener( The entire AWf event model is based on new Actionlistener() Observer. This model supersedes a Chain• { public void actionPerformed(ActionEvent e) of-Responsibility-based design that proved { System. out .println( "World"); unworkable in an 00 environment. } } ) ;

Timer t = new java.util.Timer(); Print the time once a second. The Timer t.scheduleAtFixedRate( new TimerTask() object notifies all its observers when the { public void run() time interval requested in the schedule { System.out.println(new Date().toString()); method elapses. } }, 0, 1000 ); 392 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

State Objects often need to change behavior when they are in certain states. Define an interface comprising all methods that change behavior; interface implementations define behavior for each state.

Context: Defines a public interface to the ------~ java.util.lterator outside world, methods of which change behavior with object state. Maintains an instance of a Concrete State class. * State: Defines an interface that comprises all the behavior that changes with state. Concrete State: Implements State to s - ... - , Concrete State define behavior for a particular state. (Slate '1------lsActlve .... _T_,. I +add( o: Object ) 'il I +remove( o: Object) r ""v state rState I I

What Problem Does It Solve? Pros (~) and Cons (x) Objects often need to change behavior with tl' State machines are easier to maintain since state. The "obvious" way to implement this all the behavior for a given state is in one change is for each method to contain a large place. switch statement or equivalent, with a case tl' Eliminates long, hard-to-maintain switch for each possible state, and the selector is an statements in the methods. instance variable. This structure is difficult to maintain at best, and changing the state table X State tables (indexed by current state and or introducing new states is difficult, requiring stimulus, holding the next state) are difficult many changes to many methods. to implement. In the , each state is repre• X Increases the number of classes in the sented by a State object that implements the system along with concomitant mainte• behavior of the Context object when the Context nance problems. is in a given state. An instance variable refer• X If only a few methods change behavior with ences an object that implements the current state, this solution may be unnecessarily state's behavior. A public method that changes complex. behavior with state just delegates to the current state object. To change state, modify the current state reference to reference an object that Often Confused With implements behavior for the new state. Strategy: The state objects do implement a strategy for implementing a single state, but that strategy is not provided by an outside entity.

See Also Singleton APPENDIX A DESIGN-PATTERN QUICK REFERENCE 393

Implementation Notes and Example II ... } public final class LockedCollection private final class Islocked implements Collection implements Unsafe { private final Collection c; { public boolean add(Object o) private int activeiterators o; = { throw new Exception("locked"); public boolean remove(Object o) private Unsafe active = new IsActive(); { throw new Exception("locked"); private Unsafe locked = new Islocked(); II ... private Unsafe state = active; } public LockedCollection(Collection c) { this.c = c; This code combines Decorator, Abstract } Factory, and State. It implements a Collection public Iterator iterator() that changes behavior when iterators are { final Iterator wrapped = c.iterator(); ++activeiterators; active. Active means that an iterator has been state = locked; created, but the last element of the Collection has not been examined through that iterator. return new Iterator() (Java's Collection implementations do just { private boolean valid = true; that, but it makes a good example.) The class II ... tosses an exception if you attempt to modify a public boolean hasNext() collection while iterators are active. { return wrapped.hasNext(); The Unsafe interface defines those } Collection methods that are public Object next() unsafe to call during iteration. This { Object next = wrapped.next(); interface is implemented if( !hasNext() ) by two classes: IsActive implements normal { if( --activeiterators == o ) collection behavior. Is locked implements the state = active; iterators-are-active behavior. The classes are valid = false; Singletons whose instances are referenced by active and locked. The variable state defines return next; the current state and points to one or the other } of the Singletons. }; Public methods that don't change state } public int size() with behavior (such as size ()) delegate to the { return c.size(); contained Collection, c. Public methods that public boolean isEmpty() do change state (such as add(Object)l delegate { return c.isEmpty(); } to whichever state object is referenced by II ... state. The i terator () method forces a change II Collection methods that don't of state to locked when it issues an iterator. It II change behavior are defined here. also increments an active-iterator count. This count is decremented by the Iterator's next() public boolean add(Object o) method when it reaches the last element, and {return state.add(o);} when the count goes to zero, the active state public boolean remove(Object o) is {return state.remove(o);} activated. The iterator also changes behavior with private interface Unsafe state, but only one method is affected, so the { public boolean add(Object o); State pattern isn't used. public boolean remove(Object o); No reason exists why you can't create new II ... objects each time a state transition is made. } This way the individual state object can itself private final class IsActive keep local state information. implements Unsafe { public boolean add(Object o) {return c.add(o);} public boolean remove(Object o) {return c.remove(o);} 394 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Strategy • Define an interlace that defines a strategy for executing some algorithm. A family of interchangeable classes, one for each algorithm, implements the interlace.

Protlll:tiiHMHIItlr Strategy: An interlace that allows access to an algorithm. +proc8SS( host Siring, port lnt) +sstPoolingStratB{JY( pool; Sock61Pool} Concrete Strategy: Implements a Socketl'ool•lntslface• /Context particular algorithm to conform to +a/locllts (host Siring, port int} j>OOI <; I the Strategy interlace. +1'8/eas8( s: SockBt} I I Strategy I Context: Uses the algorithm ------,.,. ... - ... _, through the Strategy interlace. tt ,...... "1 Strategy__ , .... """ ) ,. ... """ I ------I .,..- l Concrete ... r Concrete 1 I I I Strategy .,""*' I Strategy SlmplePool KeepallvePool

.n~llocate( host: Strl ng, port: int) +allocatE( host: String, port: lnt) +1'81ease; s: Socket) +release; s: SOCket )

What Problem Does It Solve? tl The Strategy object concentrates algorithm• specific data that's not needed by the Context Sometimes, the only difference between class in a class of its own. subclasses is the strategy that's used to perlorm some common operation. For tl It's easy to add new strategies to a system, example, a frame window may lay out its with no need to recompile existing classes. components in various ways, or a protocol X Communication overhead is small. Some of handler may manage sockets in various ways. the arguments passed to the Strategy You can solve this problem with derivation• objects may not be used. several frame derivatives would each lay out subcomponents in different ways, for example. This derivation-based solution creates a prolif• Often Confused With eration of classes, however. In Strategy, you Command: Command objects are very generic. define an interlace that encapsulates the The invoker of the command doesn't have a strategy for perlorming some operation (such clue what the Command object does. A Strate~ as layout). Rather than deriving classes, you object perlorms a specific action. pass the Context class the strategy it uses to perform that operation. See Also Command Pros (vo) and Cons (x) t1 Strategy is a good alternative to subclassing. Rather than deriving a class and overriding a method called from the superclass, you implement a simple interlace. APPENDIX. A DESIGN-PATTERN QUICK REFERENCE 395

Implementation Notes and Example The previous code implements a skeleton protocol handler. Some of the hosts that the interface SocketPool { Socket allocate( String host, int port handler talks to require that sockets used for void release ( Socket s ) communication are closed after every message is processed. Other hosts require that the same class SimplePool implements SocketPool socket be used repeatedly. Other hosts may have { public Socket allocate(String host,int port) other requirements. Because these requirements { return new Socket(host, port); are hard to predict, the handler is passed a } socket-pooling strategy. public void release(Socket s) The default strategy (SimplePool) simply { s.close(); opens a socket when asked and closes the } it. }; socket when the ProtocolHandler releases class KeepalivePool implements SocketPool The Keepali vePool implements a different { private Map connections = new HashMap(); management strategy. If a socket has never been public Socket allocate(String host,int port) requested, this second strategy object creates it. { Socket connection = When this new socket is released, instead of (Socket)connections.get(host+":"+port); closing it, the strategy object stores it in a Map if(connection == null) keyed by combined host name and port number. connection = new Socket(host,port); The next time a socket is requested with the return connection; same port name and host, the previously created } socket is used. A more realistic example of this public void release(Socket s) { String host = second strategy would probably implement s.getinetAddress().getHostName(); notions such as aging, where a socket would be connections. put( host+": "+s .get Port(), s ) ; closed if it hadn't been used within a certain time } frame. I I ... In the interest of clarity, I've left out the } . class ProtocolHandler { SocketPool pool = new SimplePool(); public void process( String host, int port { Socket in = pool.allocate(host,port); I I ... pool.release(in); } public void setPoolingStrategy( SocketPool p) { pool = p; } }

Usage JFrame frame = new JFrame(); The LayoutManger (Flowlayout) defines a frame.getContentPane().setlayout( new Flowlayout() ); strategy for laying out the components frame.add( new JLabel("Hello World"); in a container (JFrame, the Context).

String[] array= new String[]{ ... }; The Arrays. sort ( ... ) method is passed Arrays. sort an array to sort and a Comparator that ( array, defines a strategy for comparing two new Comparator array elements. This use of Strategy { int Compare( Object ol, Object o2 ) makes sort ( ... ) completely generic• { return ((String)o1).compareTo((String)o2); it can sort arrays of anything. }

); 396 APPENDIX A DESIGN-PATTERN QUICK REFERENCE

Template Method Define an algorithm at the superclass level. Within the algorithm, call an abstract method to perform operations that can't be generalized in the superclass. This way you can change the behavior of an algorithm without changing its structure.

algorithm that uses Abstract Class Abstract Class: Defines an l'nllocoiHallcl a ' "primitive" operations that are supplied by -+llfOCIII( host string, port lnt) ' ' subclass. ' ' ...... -- #alocale(host: string, port lnt): Socket , ~Template' ', Concrete Class: Implements the "primitive" #release(s: Socket) I I Method , ,' >- ...... __ , operations. , , f , , Keepallvef>rotocollllndler Concrete Class #lllocale (host: strilg, port lnt): Socket #rei-( s: Socket)

What Problem Does It Solve? Template method does not prohibit the class designer from providing useful default func• is typically used in deriva• Template Method tionality at the superclass level, expecting that frameworks. The frame• tion-based application the programmer will modify the behavior of that do 90 work provides a set of superclasses the superclass through derived-class over• application• percent of the work, deferring rides if necessary. In an 00 system, though, to abstract methods. That specific operations using derivation to modify superclass call abstract template is, superclass methods behavior is just run-of-the-mill programming use the framework by deriving methods. You that's hardly worth glorifying as an official classes that implement this application• pattern. specific behavior by providing template• method overrides. ~ One reasonable application of Template Method is to provide empty "hooks" at the superclass level solely so that a programmer Pros (~) and Cons (•) can insert functionality into the superclass • Template method has little to recommend via derivation. it in most situations. Strategy, for example, typically provides a better alternative. Well• Often Confused With done class libraries work "out of the box." You should be able to instantiate a frame• Factory Method: Factory Method is nothing work class, and it should do something but a Template Method that creates objects. To useful. Generally, the 90/10 rule applies be a template method, you must intend for a (10 percent of the functionality is used 90 subclass to override the template method in percent of the time, so the 10 percent should order to change the behavior of a superclass define the default behavior of the class). In method that calls the template method. template method, however, the framework often defines no default behavior, but rather See Also you are required to provided subclasses for Factory Method the superclass to do anything useful. Given the 90/10 rule, this means you have to do unnecessary work 90 percent of the time. APPENDIX • A DESIGN-PATTERN QUICK REFERENCE 397

Implementation Notes and Example This example comes from the reference Strategy, rewritten to use Template class Protoco1Hhandler2 page for { protected Socket allocate(String host,int port) Method. Rather than provide a Strategy object, { return new Socket(host, port); you derive a class that modifies the superclass } behavior. Put differently, you modify the protected void release(Socket s) behavior of the protocol-processing algorithm { s.close(); with respect to socket management by over• } riding a method that implements that algo• rithm. public void process( String host, int port ) Note that the class in the Abstract Class { Socket in = role (ProtocolHandler) is not actually abstract. socketPool.allocate(host,port); I I ••. In this reification, the superclass provides socketPool.release(in); reasonable default behavior that a subclass } can modify. Also note that the template } methods are protected, almost always the case for template methods because they are not class KeepaliveProtocolHandler extends intended for outside access. (Ignore the fact Protoco1Handler2 that Java grants package access to protected { fields--that is really a design flaw in the private Map connections = new HashMap(); language.) public Socket allocate(String host,int port) { Socket connection = (Socket)connections.get(host+": "+port);

if(connection == null) connection = new Socket(host,port); return connection;

public void release(Socket s) { String host= s .getinetAddress (). getHostName(); connections. put( host+":" +s .get Port(), s); } }

Usage class MyPanel extens JPanel Define painting behavior by overriding the paint ( •.. ) { public void paint( Graphics g ) method. You could easily do the same thing by { g.drawString("Hello World", 10, 10); passing a Panel a "paint" strategy. } 398 APPENDIX • A DESIGN-PATTERN QUICK REFERENCE

Visitor Add operations to a "host" object by providing a way for a visitor-an object that encapsulates an algorithm-to access the interior state of the host object. 1YPically, this pattern is used to interact with elements of an aggregate structure. The visitor moves from object to object within the aggregate.

Visitor: Defines an interface that allows access to a Concrete Element of an Object Structure.

+-.cturr(CUIIIIIII: ff4 defllltint, Clltllenls RleO J; Various methods can access +rllllflo(cummt ff4 dellllt lilt); elements of different types. Concrete Visitor: Implements an operation to be performed on the Elements. This object can store an algorithm's local state. Element: Defines an "accept" operation that permits a Visitor to access it. Concrete Element: Implements the "accept" operation. Object Structure: A composite object that can enumerate its elements.

What Problem Does It Solve? Often Confused With Visitor's primary use is to effectively add lterator: A Visitor is a lot like an internal methods to a class without needing to derive (passive) iterator. The main difference is that classes. Visitors can also collect information or the visitor object is passed from node to node. perform operations on all the elements of some In Iterator, the nodes are passed, one at a time, aggregation. For example, a Visitor could test all to the iterator. The Visitor structure is different the elements of an aggregation for consistency. than the Iterator structure in that it gives the element control over whether to accept the Pros (II) and Cons (x) visitor. t/ It's easy to add operations that haven't Strategy: A Visitor is, in a way, a "visiting thought of yet. strategy." The focus of visitor is to visit every node of a data structure and do something. t/ Allows the class to be smaller since rarely Strategy is much more general and has no used operations can be defined externally. connection to a data structure. t/ Visitors can accumulate state as the visit elements. A "mobile agent" can visit remote See Also objects (database servers, for example) and accumulate a composite result from a Strategy, lterator distributed database. X The internal structure of the composite object is sometimes opened to the visitor, violating encapsulation. For example, an evil visitor could be passed to elements of a tree and change their "key" values, thereby turning the tree to garbage. The visitors are tightly coupled to the object they are visiting. APPENDIX A DESIGN-PATTERN QUICK REFERENCE 399

Implementation Notes and Example Print a directory tree like this: class Directory class DirectoryPrinter { implements Directory.Visitor public interface Visitor public void visitFile(File f, int depth) { void visitFile(File current, int depth); {} void visitDirectory( File current, public void visitDirectory( File f, int depth, File[] contents ); int depth, File[] children) { while( --depth >= o ) public interface Element System.out.print(" .. "); { void accept( Visitor v, int depth ); System.out.println( f.getName() ); } } public class DirectoryElement implements Element Directory d = new Directory("c:l"); { private File f; d.traverse( new Printer() ); public DirectoryElement(File f){this.f=f;} public void accept( Visitor v, int depth ) The implementation at the left is a bit { v.visitDirectory(f,depth,f.listFiles()); more complex than it needs to be so that I } could demonstrate the general structure of } traversing a heterogeneous composite object. public class FileElement implements Element The key feature ofVisitor is that it provides { private File f; a way to add methods to an existing class public FileElement(File f){this.f = f;} without having to recompile that class. To my public void accept( Visitor v, int depth ) mind, that means that the "composite" could { v.visitFile( f, depth ); } legitimately contain only one element. } Consider this class: II======class Money private File root; { long value; II value, scaled by 100 public Directory(String root) Money increment( Money addend { this.root = new File(root); { value+= addend.value; } return value; } public void traverse( Visitor visitor ) II ... { topDown( root, visitor, 0 ); public interface Modifier// visitor } { long modify(long current); } private void topDown( File root, operate( Modifier v ) Visitor visitor, int depth ) { value = v.modify(value); Element e = } root.isFile() } (Element)(new FileElement(root)) (Element)(new DirectoryElement(root)) It's impractical to define every possible operation on money, but you can effectively add an operation by implementing a Visitor e.accept( visitor, depth ); (Modifier). Compute the future value of money like this: if( !root.isFile() ) { class FutureValue impelements Money.Modifier File[] children = root.listFiles(); { FutureValue(float interest,int period) for(int i = o; i < children.length; ++i) {!* ... *!} topDown(children[i],visitor,depth+l); public long modify( long currentValue ) } { II return future value of currentValue } } } Money presentValue = new Money(looooo.oo); money.operate( new FutureValue(.OS,24) ); About the Author

A algorithms Abstract class, defined, 396 defined, 20 Abstract Cursor Factory, 221 recursive algorithms, 98 anonymous-inner-class mechanism, 69 Abstract Factory (Collection) approve()method,231,324 (code listing), 68-69 architecture of, 7-8, 67-70, 197 Action/Control user-interface vs. Builder, 350 architecture, 117 creating tables and, 198-202 as, 364 defined, 80 of database classes, 188-189 dynamic creation in, 73-75 of Model/View/Controller (MVC), 15-16 vs. Factory method, 350, 354 ArithmeticExpression, 300,310 Game of Life and, 166-168 Arnold, Ken, 7, 10, 13 quick reference, 350-351 Arraylterator class, 217-219, 339 and, 59--61 Arraylterator.java (code listing), 217-219 Abstract product, defined, 350 ArrayList class, 41-42 AbstractButton superclass, 173 arrays, sorting, 76-77 abstractions. See also data abstraction AtornicExpression, 298,315,320 abstraction classes, 365 attributes defined, 364 defined,173 abstract-syntax tree, 298-300,310 synthesized attributes, 173-174 acceptsURL( ...) method, 329 AutoComrnitBehavior interface, 334 accessor function, 388 autoComrnitState field, 334 accessors AWf Component/Container system, 110-111 accessorsynchronization,63 AWI'EventMulticaster class, 105-108 boundary-layer classes and, 32, 35 defined, 24 getterI setter issues and, 35 base classes, 41. See also fragile base classes refactoring and, 29 BeanCustomizer class, 28 Action/Control user-interface architecture, BeanDescriptor class, 28 117 Beanlnfo class, 28 ActionListener object, 119 Beck, Kent, 30, 31 active iterators. See external iterators begin( )method, 229 Adapter pattern Behavioral patterns. See also specific vs. Bridge pattern, 362, 364 Behavioral patterns vs. , 362, 368 introduction to, 8 embedded SQL and, 339-343 quick reference, 377-399 vs. , 362 Chain of Responsibility pattern, 378-379 quick reference, 362-363 , 380-381 addClockListener(... ) method, 95 Interpreter pattern, 382-383 addLine( .. . )method, 120 , 384-385 advance()method, 270 Mediator pattern, 386-387 advancePast() method, 264 , 388-389 aggregate objects, 216 Observer pattern, 390-391 agile development methodologies State pattern, 392-393 abstract code and, 55 , 394-395 architectural analogies and, 9 Template method, 396-397 Alexander, Christopher, 1, 2 , 398-399 401 402 INDEX

Bloch, Joshua, 33, 287 vs. Decorator pattern, 368 BlockingList, 369 defined, 8 border objects, 177-178 embedded SQL BorderFactory class, 177-178 Scanner class and, 270-271 bouncing, defined, 73 shortcomings of, 275-276 boundary-layer classes, and accessors and vs. Interpreter pattern, 382 mutators, 32, 35 quick reference, 378-379 bounding rectangle, defined, 17 4 Class Adapter, 340 Bridge pattern class objects, 62 vs. Adapter pattern, 341, 362, 364 Class patterns, 7 vs. , 352 classes. See also specific classes embedded SQL embedded SQL. See also Database class, inAWf, 199 embedded SQL basics of, 188 ParseFailure class, 277-279 data-storage layer, 197-198 Scanner class, 269-277 vs. , 364, 370 Game of Life, core classes, 139-161 Game of Life, 116-117, 118 Cell interface, 145-148 JDBC layer and, 344-345 Neighborhood class, 151-161 vs. Mediator pattern, 386 Resident class, 148-151 quick reference, 364-365 Universe class, 139-144, 161 BufferedinputStream class, 253 vs. interfaces, 38-55 buffering, Decorator pattern, 368 coupling, 40-41 Builder interface, 213 factory-method patterns, 50-54 Builder pattern flexible structures, 39-40 vs. Abstract Factory pattern, 350 fragile base classes, 41-47, 55 vs. Bridge pattern, 352 frameworks, 48-49 importing and exporting and, 212-213 , 47-48 passive iterators and, 202-213 template-method patterns, 49-50 quick reference, 352-353 types of, 38 vs. Visitor pattern, 352 clear( ) method, 42 business objects, and getter I setter issues, 34 client()method,68 clock subsystem, Game of Life c Observer pattern, 86-103 C language, and patterns, 1-2 introduction to, 86-92 C++ language Publisher class, 93-103 C++ SmartPointer, 287 Visitor pattern, 104-108 interfaces in, 38 clock tick message example, 168-169 procedural system in, 11 Clock.java: The Clock Class (code listing), virtual constructors in, 355 90-92 callback problems, and Command pattern, Clock.Listener derivative, 90 380 clone( ) method, 356, 357 calling method, 325 code listings (by chapter) cancel() method, 93-94 embedded SQL cancelSubscription() method, 99 Arraylterator.java, 217-219 caretakers,34, 178-179,388 ConcreteTable.java: Importing and Cartesian product, defined, 236 Exporting,204-205 Cell interface, Game of Life, 84, 145-148, 163 ConcreteTable.java: Inserting Rows, Cell.java (code listing), 145-148 215-216 Cell.Memento interface, 180 ConcreteTable.java: Miscellany, 242-249 cells, defined, 192 ConcreteTable.java: Selection and Joins, cellular automata programs, 20-24 237-241 Chain of Command pattern, 270-271, 275. ConcreteTable.java: Simple Table See also Chain of Responsibility Creation, 202-204 pattern ConcreteTable.java: Transaction Chain of Responsibility pattern Support, 229-231 vs. Composite pattern, 366, 378 ConcreteTable.java: Thaversing and Neighborhood.java, 151-161 ~odll)1ng,22l-222 Observer, Implementing with a ConcreteTable.java: Updating and Publisher Object, 95-96 Deleting, 234 Publisher. java: A Subscription ~anager, ConnectionAdapter.java (Partial listing), 99-103 331-332 Resident.java, 148-151 CSVExporter.java, 209-210 Storable.java, 179-180 CSVImporter.java, 205-206 Universe.java, 139-144 Cursor.java, 219-221 interfaces Database.java: Convenience ~ethods Abstract Factory (Collection), 68-69 That Mimic SQL, 290-293 Double-Checked Locking, 64 Database.java: Expressions, 310-315 Dynamic Instantiation, 74-75 Database.java: Interpreter Invocation, Factory Implementation, 59-61 320-324 Factory ~ethod, Using, 52-53 Database.java: Private Data and the fragile base classes, eliminating, 46-4 7 Table~ap,284-286 Singleton's, Shutting Down, 66-67 Database.java: The Parser, 301-310 Sorters. java: Using Strategy, 77-78 Database. java: Tokens and URLConnection Implementation, Enumerations, 288-290 Stripped-Down, 71-72 Database. java: Transaction Processing, collaboration symbol, 4, 51-52 294 Collaborator classes, 31 Database. java: Values, 316-318 Colleagues, 386 Database. Test.sql, 281-283 Collection class as utility class, 256 JDBCConnection.java, 334-338 Collection interface vs. Table, 192 JDBCDriver.java, 329-331 collections, and thread-safety solution, JDBCResultSet.java, 341-343 255-256 JDBCResultSet~etaData.java, 344 Color class, Java, 34 JDBCStatement.java, 338-339 Colors interface, 180 JDBCTest.java, 326-328 Colors Singleton, 180-181 JTableExporter.java, 211-212 Colors.java (code listing), 181-184 ParseFailure.java, 278-279 columns, 192 Peoplelmporter.java, 207-209 com.holub.database.jdbc.JDBCConnection, RegexToken.java, 266-267 333 Scanner.java, 271-275 Command pattern Selector.java, 232-234 defined, 80 SimpleToken.java, 264-265 Game of Life, 166-168 TableFactory.java, 200-202 implementing transactions (undo) and, Table.java, 192-196 226-231 ThrowableContainer.java, 325 vs. ~emento pattern, 388 Token.java, 264 vs. Observer pattern, 390 TokenSet.java, 267-269 quick reference, 380-381 Tree. java: A Simple Binary-Thee vs. Strategy pattern, 380, 394 Implementation, 223-226 Strategy pattern and, 75-79 UnmodifiableTable.java, 250-252 committing transactions, 227 WordToken.java, 265-266 compile-time type checking, 57 GameofLife Component superclass, 173 Cell.java, 145-148 Composite pattern Clock.java: The Clock Class, 90-92 vs. Chain of Responsibility pattern, 366, Colors.java, 181-182 378 ConditionVariable.java, 184-185 vs. Decorator pattern, 366, 368 Direction.java, 170-172 vs. , 372 Files.java, 182-184 Life subsystem classes and, 163-172 Life.java, 118-119 clock tick message example, 168-169 ~enuing Systems, Building with the Direction.java (code listing), 170-172 Raw APis, 113-116 introduction to, 163-165 ~enuSite.java, 123-139 , 166-168 404 INDEX

Composite pattern (continued) create( ...) method, 267 menuing subsystem, Game of Life, createMenus method, 119 108-116 Creational patterns. See also specific basics of, 108-113 Creational patterns Menuing Systems, Building with Raw introduction to, 7-8 APis (code listing), 113-116 quick reference, 349-359 objects, 110--112 Abstract Factory pattern, 350--351 quickreference,366-367 Builderpattern,352-353 Concrete Aggregate, defined, 384 Factory method, 354-355 Concrete Class, defined, 396 Prototype pattern, 356-357 Concrete Factory, defined, 350 Singleton pattern, 358-359 Concrete Flyweight, 372 Creator, defined, 354 Concrete Mediator, defined, 386, 387 Cross Ventilation, 3, 4 Concrete Observer/Subscriber role, 89-90 Crypto APis, and implementation, 36 Concrete State, 392 CSVExporter class, 209 Concrete Strategy, 394 . CSVExporter.java (code listing), 209-210 Concrete Visitor, 104-105, 398 CSVImporter class, 205-206, 213 ConcreteBuilder, 212 CSVImporter.java (code listing), 205-206 ConcreteTable, 189-191 Cunningham, Ward ConcreteTable.java code listings CRC-Card format and, 18, 30--31 ConcreteTable.java: Importing and get/ set mentality and, 30 Exporting (code listing), 204-205 Cursor interface, 218, 221 ConcreteTable.java: Inserting Rows (code Cursor objects, 340 listing), 215-216 Cursor.java (code listing), 219-221 ConcreteTable.java: Miscellany (code cut and paste approach, 5 listings), 242-249 ConcreteTable.java: Selection and Joins D (code listing), 237-241 data ConcreteTable.java: Simple Table Creation databases as caretakers of, 34 (code listing), 202-204 extrinsic data, defined, 17 4 ConcreteTable.java: 'fransaction Support importing and exporting to tables, (code listing), 229-231 204-205 ConcreteTable.java: Updating and data abstraction, 10, 13, 26, 38 Deleting (code listing), 234 Database class, embedded SQL, 279-294 ConditionVariable class, 181, 184 methods of, 281 ConditionVariable.java (code listing), , 283-287 184-185 supported SQL and, 295 connect()method,329 token set and other constants, 287-294 ConnectionAdapter class, 331 using databases, 280--281 ConnectionAdapter.java (Partial Listing), Database.java code listings 331-332 Database.java: Convenience Methods constant fields, and public fields, 41 That Mimic SQL (code listing), constant values, 33 290--293 Container superclass, 173 Database.java: Expressions (code listing), Context, defined, 392 310--315 contracts Database.java: Interpreter Invocation defined, 14 (code listing), 320--324 objects defined by, 13-14 Database.java: Private Data and the controllers, 390 TableMap (code listing), 284-286 Conway, John, 81 Database.java: The Parser (code listing), cookies, 178 301-310 Cooper, Alan, 7 Database. java: Tokens and Enumerations copy-on-write strategy, 374 (code listing), 288-290 coupling, and implementation inheritance, Database.java: 'fransaction Processing 40--41 (code listing), 294 course-grained operations, 27 Database. java: Values (code listing), CRC-Card format, 18, 30--31 316-318 1.1 ND EX 405

databases. See also embedded SQL design patterns, purpose of, 5-6 as caretakers of data, 34 get and set methods, 24-36 using, 280-281 basic issues of, 34-36 Database.Test.sql (code listing), 281-283 design, creating without getters and data-storage classes, and database setters, 30-32 arctritecture, 188-189 examples, 24-27 data-storage layer, embedded SQL, 189-258 JavaBeans and Struts, 28-29 Abstract-Factory and creating tables, refactoring, 29-30 198-202 when to use, 32-34 Bridge pattern, 197-198 00 basics, 12-19 Decorator pattern, 250-258 objects, capabilities of, 13-14 Iterator pattern, 216-226 objects, defined, 13 miscellany, 241-249 00 systems, right and wrong examples, passive iterators and Builder, 202-213 15-19 selection and join operations, 235-241 00 design basics, 9-10 Strategy pattern, 231-234 patterns Table interface, 192-196 classifying, 7-8 transactions (undo), implementing with role of in design, 6-7 Command pattern, 226-231 patterns vs. idioms, 1-2 DCL (Double-Checked Locking), 64-65 programming Decorator pattern informed choices in, 12 vs. Adapter pattern, 341, 362, 368 programming in Java, 9-10 vs. Chain of Responsibility pattern, 368 Design Patterns: Elements ofReusable Object• vs. Composite pattern, 366, 368 Oriented Software (Addison-Wesley, embedded SQL, 250-258 1995). See also GangofFour immutability and, 172 consequences section in, 12 vs. Proxy pattern, 287,374 extends keyword and, 37 quick reference, 368-369 patterns and, 1, 3, 5, 7 delegation Direction class, 170-172 defined, 22 Direction.java (code listing), 170-172 delegation models, and implementation, Director, defined, 352 46 directories delete() method, 221 directory files, defined, 111 delivetro()metllod,95,104 directory systems, traversing, 112 Derivation pattern, 1-2 directoryName request, 280 derived class, 44-45 dolnsert() method, 214 design doLoad()method,l79 creating without getters and setters, 30-32 domain modeling, 32 informed choices in, 12 doSelect() method, 319,324 role of patterns in, 6-7 doStore() method, 179 design patterns. See also specific patterns Double-Checked Locking (code listing), 64 basics of, 2-5 Double-Checked Locking (DCL), 64-65 classifying, 7-8 DUMMY objects, Game of Life, 177 Game of Life, 86 dump()method,289-290 overlapping combination of, 70-72 dynamic creation in a factory, 73-75 patterns diagrams, 84 dynamic loading, 356 patterns vs. idioms, 1-2 dynamic model, defined, 31 purpose of, 5-6 quick reference. See quick reference, E design patterns Eclipse role of in design, 6-7 refactoring and, 29 SQL engine and JDBC layers, 260 SWT library, 345 design patterns and 00 (object orientation), edge(... ) metllod, 176 1-36 Editor class, example, 49 cellular automata programs, 20-24 EditorKit, and HTML parsing, 51-52 design patterns basics, 2-5 Effective Java Guide (Addison-Wesley, 2001), 33 406 INDEX

embedded SQL, 184-345 traffic modeling, using cellular arctritecture, 188-189 automata, 20-24 Database class, 279-294 11 god II class, 30 Proxy pattern, 283-287 interfaces token set and other constants, 287-294 Editor class, 49 using databases, 280-281 hUgh-water/low-water, 43-45 data-storage layer, 189-258 Java, framework, 48-49 Abstract-Factory and creating tables, of Singleton pattern, 61-62 198-202 execute( ...) method, 281, 310 Bridge pattern, 197-198 executeUpdate( ... ) method, 332, 338 Decorator pattern, 250-258 export() method, 209, 222 Iterator pattern, 216-226 Exporter, building, 209-210 miscellany, 241-249 exporting data to tables, 204-205 passive iterators and Builder, 202-213 Expression objects, 298, 300, 315 selection and join operations, 235-241 Expressions (code listing), 310-315 Strategy pattern, 231-234 extends keyword Table interface, 192-196 appropriate use, 56-58 transactions (undo), implementing eliminating,58-79 with Command pattern, 226-231 Abstract Factory, 67-70 Interpreter pattern, 295-325 command patterns and strategy demonstration of, 318-325 patterns, 75-79 supported SQL, 295-318 Double-Checked Locking (DCL), 64-65 JDBC layer, 325-332 dynamic creation in a factory, 73-75 requirements, 187-188 factories and Singletons, 59-61 SQL, adding, 259-279 patterns, overlapping combination of, input tokenization, 262-269 70-72 ParseFailure class, 277-279 Singleton pattern examples, 61-62 Scanner class, 269-277 Singletons, eliminating, 65-67 SQL-engine structure, 260-261 Singletons, threading issues in, 62-64 State pattern and JDBCConnection class, programming with interfaces and, 37-38 332-345 external iterators, 222, 384, 385, 393 Adapter pattern (result sets), 339-343 extrinsic data, defined, 17 4 Bridge pattern and, 344-345 JDBCResultSetMetaData class, 344 F statements, 338-339 Facade pattern tables. See tables, embedded SQL vs. Bridge pattern, 364, 370 encapsulation eliminating clutter and, 27 encapsulation principle, 26 Game of Life, 116-118 encapsulation requirements, 22 vs. Mediator pattern, 162, 370, 386 implementation and, 36 menuing subsystem, 116-117 enums,defir.Ung,33 quick reference, 370-371 error(. ..) method, 289 factor( ...) method, 315 evaluate method, 310, 319, 320, 324 Factory Implementation (code listing), 59-61 everything-is-static Singleton, 119 Factory method examples vs. Abstract Factory pattern, 350, 354 clock tick message, 168-169 defined, 80 design patterns and 00 quick reference, 354-355 arctritecture pattern, 3-4 vs. Template method, 396 ATMsystem, 17-19 Factory pattern. See Abstract Factory pattern get and set methods, 24-27 factory-method patterns, 50-54 getK()method,24-25 fields. See public fields multiple currencies, 24-25 figureNextState( ) method, 176 right and wrong examples, 15-19 FilelnputStream class, 253 System.in, System.out, 25 Files.java (code listing), 182-184 traffic modeling, getter and setter final keyword, Java, 33 methods,26 fine-grained operations, 27 IINDEX 407

fireEvent()metl1od,93-94 get and set metllods, 24-36 flexible structures, and interfaces, 39-40 basics of, 34-36 flush( ...) metllod, 179 cellular automata programs and, 22-23 Flyweight pattern design, creating Mtllout getters and vs. Composite pattern, 372 setters, 30-32 Game of Life, 172-178 examples, 24-27 basics of, 172-176 JavaBeans and Struts, 28-29 flyweight pools, 176-178 refactoring,29-30 push model and, 35 ~hen to use, 32-34 quick reference, 372-373 getDefaultToolkit() metllod, 75 forName( ...) metllod, 328 getDirty()metl1od,215 FORTRAN programming, Java, 9-10 getRo~DataFromUser() metllod, 206 fragile base classes, 41-47,55 get/ set idioms, JavaBeans, 28 Fragile Base classes, Eliminating (code getK()metl1od,exarnple,24-25 listing), 46-47 Go menu, Game of Life, 109 Frame~orks,48-49 "god" classes, 25,30 function pointers, defined, 75 Goldberg, Adele, 37 Gosling, James, 35, 38 G grammar, SQL-subset, 296-297 Game of Life implementation, 81-185 Graphics class, 162 basics and rules of, 82-83 Grid menu, Game of Life, 109, 162 charting structure of, 83-86 GridLayout objects, 173 clock subsystem, Observer pattern, 86-103 H introduction to, 86-92 HashMaps, 283-284 Publisher class, 93-103 heterogeneous lists, 104 clock subsystem, Visitor pattern, 104-108 HTML parsing, 51 Composite pattern, and Life subsystem classes, 163-168 [I Composite redux, 168-172 IDENTIFIER token, 262, 271 core classes, 139-161 identifiers, 295 Cell interface, 145-148 idioms in programming Neighborhood class, 151-161 Bloch's typesafe-enurn idiom, 287-288 Resident class, 148-151 get/set idioms, 28 Universe class, 139-144 implement/ delegate idiom, 48 Flyweight pattern, 172-178 vs. patterns, 1-2 basics of, 172-176 idList()metl1od,319 flyweight pools, 176-178 IdValue class, 315 Mediator pattern, 161-162 Image proxy, 334 Memento pattern, 178-180 Immutable class, 172 menuing subsystem immutable classes, 33 Bridge pattern, 116-117, 118 implementation Composite pattern, 108-116 encapsulation of, 35-36 Facade pattern, 116-117 exposing, 34 MenuSite class, 117-139 hiding,l0,26,34-35 Life.java (code listing), 118-119 implementation inheritance. See also MenuSite documentation, 120-121 extends keyword MenuSite.java (code listing), 123-139 adding to collections and, rniscellaneous,l80-185 254 summary of, 185 adding unrnodifiability to collections and, Gang ofFour. See also Design Patterns: 255-256 Elements ofReusable Object-Oriented assigning tables and, 252 Software (Addison-Wesley, 1995); implementation-inheritance-based quick reference, design patterns solutions in Game of Life, 87-88 consequences section in book, 12 vs. interface inheritance, 37-38 design patterns, 1, 3, 7, 8, 55 reification and, 7 Singleton pattern, 62-63, 64 408 INDEX

Importer Singleton pattern examples, 61-62 building, 205-206 Singletons, eliminating, 65-67 Peoplelmporter.java (code listing), Singletons, threading issues, 62-64 207-209 extends keyword, 37-38 importing data to tables, 204-205 GameofLife inheritance. See also implementation Cell.Memento interface, 180 inheritance Colors interface, 180 coupling and, 40-41 Interface Adapter, 340 fragile-base-class problem and, 41-47 interface inheritance, 7, 252 interface inheritance vs. implementation ResultSet interface, 341 inheritance, 37-38 summary of, 80 multiple inheritance, 47-48 use of in patterns, 7 structure, and operations, 57 internal iterators, 202-213, 222-226, 384 INPUT token, 264, 270-271 Interpreter Invocation (code listing), 320-324 input tokenization, embedded SQL, 262-269 Interpreter pattern InputStream derivatives, 71 vs. Chain of Responsibility pattern, 382 instantiation embedded SQL, 295-325 lazy instantiation, 283 basics of, 310 patterns and, 3 demonstration of, 318-325 Instantiation Dynamic (code listing), 74-75 supported SQL, 295-318 intent, defined, 3 quick reference, 382-383 Interface Adapter, 340 Invoker (Thread object), 226 interfaces, 37-80 is-a relationstrip, 57 Action/Control user-interface isDirty() method, 215, 290 arctritecture, 117 isDisruptiveTo method, 153, 170 Bridge pattern as, 364 Iterator pattern Cell interface, Game of Life, 84, 145-148, embedded SQL, 216--226 163 Iterator objects, 197 Cell.Memento interface, 180 quick reference, 384-385 vs. classes, 38-55 vs. Visitor pattern, 384, 398 coupling, 40-41 iterators factory-method patterns, 48-54 Arraylterator.java (code listing), 217-219 flexible structures, 39-40 external,222,384,385,393 fragile base classes, 55 internal,222-226,384 fragile-base-class problem, 41-47 Iterator objects, 197 frameworks, 48-54 modifying data structure and, 218 multiple inheritance, 47-48 passive iterators, and Builder, 202-213 template-method patterns, 48-54 embedded SQL AutoCommitBehavior interface, 334 Java• Builder interface, 213 Color class, 34 Collection interface vs. Table, 192 compiler-compilers, 259 Cursor interface, 218,221 final keyword, 33 ResultSet interface, 341 FORTRAN programming in, 9-10 Selector interface, 232 framework example, 48-49 Table interface, 188-189, 192-196,221 Graptrics class, 162 Table.Importer interface, 204 Java libraries, 35-36, 81 extends, appropriate use of, 56-58 JavaCC,259 extends, eliminating, 58-79 JavaCUP, 259 Abstract Factory, 67-70 LayoutManager, 78 command patterns and strategy procedural programming and, 25 patterns, 75-79 Toolkit Singleton, 75 Double-Checked Locking (DCL), 64-65 when to use, 16--17 dynamic creation in a factory, 73-75 The Java Class Libraries (Addison-Wesley), factories and Singletons, 59-61 347 patterns, overlapping combination of, java.awt.Color values, 180 70--72 java.awt.Toolkit, 197,355 'l!NDEX 409

java.awt.Wmdow class, 197 JavaBeans key• abstractions, defined, 32, 112 get and set methods and, 28-29 keyboard shortcuts, 123-124 get/setidioms,28 keyword tokens, 287 java.io.StreamTokenizer, 262 keywords. See also extends keyword java.lang.Double class, 315 final keyword, 33 JavaServer Pages, and Memento pattern, 179 synchronized keyword, 64 java.sql.Connection object, 329 volatile keyword, 65 java.sql.Connection's createStatement() call, 338 java.sql.DriverManager class, 328, 329 label.. parameter, 123 java.sql.ResultSet object, 338 LayoutManager, Java, 78 java.sql.Statement object, 338 lazy instantiation, 283, 374 java.text.NumberFormat class, 27, 198, 295 Leaf, defined, 366 java.util.Iterator, 204, 221, 267 Leaf objects, 110 java.util.StringTokenizer, 262 lexeme()method,264 java.util.Timer object, 119 lexemes,262-263 javax.Swing.Border, 177 Life class, Game of Life, 161-162 JButton class, 173 Life subsystem classes, Game of Life, 163-168 JButton derivatives, 172 Life.java (code listing), 118-119 JComponent class, Game of Life, 88-89 LinkedList class, Game of Life, 96 I Component superclass, 173 listener parameter, 121 JDBC load( ...) method, 179, 200 JDBC Bridge, 365 JDBC layer, 325-332 jdbcCompliant() override, 328 ... main(... ) method, 328 JDBCConnection class, 331, 332-345 maintenance JDBCDriver class, 328 maintenance problems, 18 JDBC-driver layer, 188-189 ofprograms,34-35 JDBCResultSet class, 339-343 maps of names, 122 JDBCResultSetMetaData class, 344 MarkupPanel, Factory method in, 54 State pattern and JDBCConnection class, match( ...) method, 264, 270 332-345 match(String input) method, 264 Adapter pattern (result sets), 339-343 Mediator pattern Bridge pattern and, 344-345 vs. Adapter pattern, 362 JDBCResultSetMetaData class, 344 vs. Bridge pattern, 386 statements, 338-339 vs. Facade pattern, 370, 386 JDBC code listings Game of Life, 161-162 JDBCConnection.java (code listing), quick reference, 386-387 334-338 Memento pattern JDBCDriver.java (code listing), 329-331 attribute representations and, 28 JDBCResultSet.java (code listing), 341-343 vs. Command pattern, 388 JDBCResultSetMetaData.java (code data blobs and, 117 listing), 344 GameofLife, 178-180 JDBCStatement.java (code listing), quick reference, 388-389 338-339 memory barriers, 65 JDBCTest.java (code listing), 326-328 menu items, adding, 112-113 JEditorPane class menuing subsystem, Game of Life rewrite of, 79 Bridge pattern, 116-117, 118 Swing and, 50--51 Composite pattern, 108-116 JFrame object, 172-173 Facade pattern, 116-117 join and selection operations, embedded Menuing Systems, Building with the Raw SQL, 235-241 APis (code listing), 113-116 JTableExporter class, 210--212, 213 MenuSite class, Game of Life, 117-139 JTableExporter.java (code listing), 211-212 Life.java (code listing), 118-119 MenuSite documentation, 120--121 MenuSite.java (code listing), 123-139 410 INDEX

menuSpecifier object, 121 Object-Oriented Programming (OOP), vs. menuSpecifier parameter, 122 OOD,9-10 metadata, table, 204 objects methods. See also specific methods capabilities of, 13-14 of Database class, 281 class objects, 62 Microsoft Composite pattern objects, 11Q-112 Excel, 117, 178 defined, 13 Microsoft applications, 00 systems and, JMenultem, 110 11 Leaf objects, 110 Microsoft's Foundation Class (MFC), 48 menuSpecifier object, 121 Microsoft's Object-Linking-and• requester object, 120 Embedding In-Place-Activation traversing collections of, 108 system, 117 Observer, Implementing with a Publisher Word, 117, 178 Object (code listing), 95-96 Model/View I Controller (MVC) architecture Observer pattern basics of, 15-16 vs. Command pattern, 390 Struts and, 28-29 Game of Life, 86-103. See also Publisher modilY()method,231 class Money class, 24 introduction to, 86-92 MotifToolkit, 197 quick reference, 39Q-391 mouse clicks, 17 4-175 vs. Strategy pattern, 390 multiple currencies examples, 24-25 00 (object orientation), 12-19. See also multiplicativeExpression() method, 300,310 design patterns and 00 (object mutators orientation) boundary-layer classes and, 32, 35 basics of defined, 24 objects, capabilities of, 13-14 getter I setter issues and, 35 objects, defined, 13 refactoring and, 29 00 systems, right and wrong examples, MVC. See Model/View/Controller (MVC) 15-19 architecture 00 design basics, 9-10 openConnection() method, 73 N operations name parameter, 121, 123 course-grained vs. fine-grained, 27 Neighborhood class, Game of Life, 84, inheritance structure and, 57 151-161,174,176 Originator, defined, 388 Neighborhood objects, 163-167, 169-170 Neighborhood.java (code listing), 151-161, p 166 parameters, MenuSite class, 121}-121, 122, Neighborhood.NeighborhoodState class, 123 160,180 ParseError object, 289 nested transactions, 227,332 ParseFailure class, embedded SQL, 277-279 Node class, Game of Life, 96 ParseFailure exception, 324 Node objects, Game of Life, 97 ParseFailure.java (code listing), 278-279 nodes, 298 The Parser, Database.java (code listing), Nonterminal expressions, 319 301-310 nonterminal nodes, 298 parsers normalization class, 56 parserrequirement,262 numbers forms, 295 parsers, and lookahead tokens, 269-270 NumericValue method, 315 recursive descent parser technology, 259 SQL parser, 295, 296 0 parsing HTML, 51 Object Adapter, 340 passive iterators, 202-213, 222-226, 384 object structure, 117 PattemHatching(Addison-Wesley, 1998), 172 Object-Oriented Design Heuristics (Addison• patterns. See design patterns; quick reference, Wesley, 1996), 358 design patterns; specific patterns Object-Oriented Design (OOD), vs. OOP, peer classes, 197 9-10 Peoplelmporter class, 206-209, 213 1NDEX 411

Peoplelmporter.java (code listing), 207-209 ll percent(%) wildcard, 295 quick reference, design patterns, 347-399 polymorphism, defined, 38 Behavioral patterns, 377-399 pools, flyweight, 176-178 Chain of Responsibility pattern, PostgreSQL driver, 345 378-379 privacy, of data in systems, 13-14 Command pattern, 380-381 private indexOf method, 202 Interpreter pattern, 382-383 problem domains, 31-32 Iterator pattern, 384-385 Procedural systems, 10-11 Mediator pattern, 386-387 programming Memento pattern, 388-389 informed choices in, 12 Observer (Publish/Subscribe) pattern, Java 390-391 Effective Java Programming Language State pattern, 392-393 Guide (Addison-Wesley, 2001), 33 Strategy pattern, 394-395 FORTRAN programming and, 9-10 , 396-397 procedural programming and Java, 25 Visitor pattern, 398-399 procedural approaches to, 10-11 Creational patterns, 349-359 programmers tendency toward Abstract Factory pattern, 350-351 complexity, 7 Builder pattern, 352-353 protection proxy patterns, 287 Factory method, 354-355 Prototype pattern Prototype pattern, 356-357 Game of Life, 166-168 Singleton pattern, 358-359 quick reference, 356-357 Structural patterns, 361-375 Proxy pattern Adapter pattern, 362-363 combined with State pattern, 334 Bridge pattern, 364-365 vs. Decorator pattern, 374 Composite pattern, 366-367 embedded SQL, 283-287 Decorator pattern, 368-369 quick reference, 374-375 Facade pattern, 370-371 public fields Flyweight pattern, 372-373 acccessors and mutators and, 41 Proxy pattern, 374-375 constant fields and, 41 dangers of, 26 IIR public static void addLine() method, 121 Real Subject available state, 334 public static void addMapping, 123 Real Subject unavailable state, 334 public static void establish method, 120 recursive algorithms, 98 public static void mapNames(URL table) recursive descent parser technology, 259 throws IOException, 122 recursive traversal, 385 public static void removeMyMenus method, refactoring, and get and set methods, 29-30 121 refined Abstraction, defined, 364 publicstatic void setEnable method, 122 RegexToken subclass, 263 Publisher class, 93-103 RegexToken.java (code listing), 266-267 introduction to, 93-95 register methods, 229 Observer, Implementing with a Publisher Reification, defined, 3 Object (code listing), 95-96 RELATIONAL_ OPERATOR token, 262 Publisher. java: A Subscription Manager RelationalExpression object, 320 (code listing), 99-103 remote proxy patterns, 287 Publisher object, Game of Life, 97 requester object, 120 Publisher Object, Implementing Observer requester parameter, 121, 122 with (code listing), 95-96 required(Token) method, 270 Publisher. java: A Subscription Manager Resident class, Game of Life, 148-151, (code listing), 99-103 163-164,174 publishers, defined, 390 . Resident objects Publish/Subscribe pattern, Game of Life, 88 "alive" and, 180 push and pull models, 35 cells and, 164 pushback, Decorator pattern, 368 Scanner class and, 269-277 put() override, 283 Resident.java (code listing), 148-151 412 INDEX

result sets, defined, 188, 235 Stack class, and ArrayList class, 42-45 Results class, 340 State pattern ResultSet interface, 341 embedded SQL ResultSetAdapter class, 331 Bridge pattern and, 344-345 ResultSetMetaDataAdapter class, 331 combined with Proxy pattern, 334 Riel, Arthur, 358 JDBCConnection class and, 332-345 roles, vs. users, 57 Adapter pattern (result sets), 339-343 rollbacks,defined,226-227 JDBCResultSetMetaData class, 344 rows statements, 338-339 described, 192 quick reference, 392-393 inserting (code listing), 215-216 vs. Strategy pattern, 392 Runnable class, 226 StatementAdapter class, 331 statements, embedded SQL, 338-339 static initializers, 63 Scanner• class static model, defined, 31 embedded SQL, 269-277 Storable.java (code listing), 179-180 ParseFailure class and, 277-278 storeRow() method, 222 Scanner.java (codelisting),271-275 stories, defined, 56 scanning,defined,262 Strategy and Sorters.java (code listing), 77-78 screen painting, 176 Strategy pattern select() method, 319, 320, 324 vs. Command pattern, 380, 394 select() overloads, 237 Command pattern and, 75-79 selectFromCartesianProduct( ...) method, defined,80 237 embedded SQL, 231-234 selection and join operations, embedded vs. Observer pattern, 390 SQL,235-241 quick reference, 394-395 Selector interface, 232 vs. State pattern, 392 Selector.java (code listing), 232-234 vs. Visitor pattern, 398 servlets StreamTokenizer, 262 defined, 276 String class implementation, 29 servletfilters,276-277,378,379 StringBufferlnputStream, 340 set methods. See get and set methods Stroustrup, Bjame, 13 setAutoComrnit() method, 334 Structural patterns. See also specific setDirty() method, 215 Structural patterns shortcut parameter, 123 introduction to, 8 shortcuts, keyboard, 123-124 quickreference,361-375 "shutdown hooks", defined, 65 Adapter pattern, 362-363 SimCity software, 24 Bridge pattern, 364-365 SimpleToken subclass, 263-264 Composite pattern, 366-367 SimpleToken.java (code listing), 264-265 Decorator pattern, 368-369 simplicity, and patterns, 6 Facade pattern, 370-371 Singleton pattern Flyweight pattern, 372-373 Abstract Factory pattern and, 59-61 Proxy pattern, 374-375 defined,80 Struts, 28-29 elirninating,65-67 Subject, and notification, 88 everything-is-static Singleton, 119 subscribe() method, Game of Life, 93-94 examples of, 61-62 subscribers Singleton, defined, 61 adding,98 threading issues in, 62-64 defined, 390 vs. Utility class, 256, 358 Subscription Manager (code listing), 99-103 Singleton's, Shutting Down (code listing), subsystem classes 66-67 defined, 370 smart reference patterns, 287,374 Life subsystem classes, 163-172 snapshot strategy, 227 clock tick message example, 168-169 Sorters.java: Using Strategy (code listing), Direction.java (code listing), 170-172 77-78 introduction to, 163-165 SQL. See embedded SQL Prototype pattern, 166-168 INDEX 413

Swing tail recursion, 298-300 caching and, 178 Template method flexibility of, 53 defined, 80 GameofLife vs. Factory method, 396 event thread and, 93 quick reference, 396-397 importance of in, 81 Template-method patterns, 49-50 Universe class and, 162 terminal nodes, 298 JEditorPane class, 50-51 ThatCellAtEdgeChangeState() method, 170 SWT library, Eclipse, 345 threading issues synchronization, accessor, 63 adding thread safety to collections, 254 synchronized keyword, 64 Command pattern and, 76 syntax, abstract-syntax tree, 298-300, 310 "shutdown hooks" and, 65 synthesized attributes, 173-174 in Singleton pattern, 62-64 A System ofPatterns: Pattern-Oriented ThreadSafecollection class, 256 Software Architecture (John Wiley & threePixelPadding object, 178 Sons, 1996), 117 ThrowableContainer class, 324-325 System.getProperty( ...), 75 ThrowableContainer.java (code listing), 325 System.in, System. out example, 25 tick( ) method, 95 systems toArray( ) , 95 OOsystems token set definition, 287-294 basics, 10 tokenization, input, 262-269 privacy of data in, 13-14 Token.java (code listing), 264 simple, 6-7 tokens creating, 263 T defined, 262 Table classes, usefulness of, 259 token type (IT), 262 Table interface, embedded SQL, 188-189, TokenSet.java (code listing), 267-269 192-196,221 Toolkit Singleton, Java, 75 table parameter, 122 Toolkit.getDefaultToolkit() method, 197 TableFactory class, 200-202 toString() method, 315 TableFactory.java (code listing), 200-202 toThisMenu parameter, 121 Table.Importer interface, 204, 213 'Ii'ansaction Processing (code listing), 294 Table.java (code listing), 192-196 transactions TableMap Private Data (code listing), transaction model, 296 284-286 undo, implementing with Command tables, embedded SQL. See also embedded pattern, 226-231 SQL transition() method, 169-170 vs. Collections, 192 traverse() method, 385 converting names to tables, 319, 320-323 traversing collections of objects, 108 creating Thee. java: A Simple Binary-Thee Abstract Factory and, 198-202 Implementation (code listing), lterator pattern and, 216-226 223-226 passive iterators and Builder and, IT (token type), 262 202-213,222-226 populating tables, 213-216 u database architecture and, 188, 190-191 UML Decorator pattern and, 250-258 UML 1.5 collaboration symbol, 4 defined, 192 UML static-model diagram (traffic model), "housekeeping", 241-249 23 modifying undo features, 7, 179, 380, 389 Strategy pattern and, 231-234 undo subsystem, and Command pattern, updating and deleting, 234 226-231 select and join operations, 235-241 Universe class selecting into other tables, 295 Game of Life, 139-144 Table interface, 192-196 Life object instantiation and, 161-162 table metadata, 204 Universe Mediator, 168-169 414 INDEX

Universe object, 89 w Universe.java (code listing), 139-144 wait() method, 181 unmodifiable collections, adding, 255-256 Web sites UnmodifiableTable class, 250-252 for downloading SimCity, 24 UnmodifiableTable.java (code listing), for further information 250-252 DCL,65 unread(... ) method, 257 Game of Life, 81 UnsupportedOperationException, 58 JavaCC,259 update() method, 221 JavaCUP, 259 URLConnection Implementation, Stripped- JDOM classes, 367 Down (code listing), 71-72 links to SQL resources, 187 use cases, 30 preseeded Life games, 83 userClicked()override,174 SwingThtorial, 81 user-input processing, 276 WmdowPeer object, 197, 199 users vs. roles, 57 Windows toolkit, 197 utilities vs. Singletons, 256, 358 WordToken subclass, 263-264 WordToken.java (code listing), 265-266 v wrapping strategy, 253 value() method, 315 Values (code listing), 316--318 X variables XMLExporter class, 213 global variables, and coupling, 40 XMLimporter class, 213 public variables, and globals, 358 virtual constructors, C++, 355 virtual proxy patterns, 287, 374 Visitor pattern vs. Builder pattern, 352 Game of Life, 104-108 vs. Iterator pattern, 384, 398 quick reference, 398-399 reification in Life, 97 vs. Strategy pattern, 398 VK_X constants, 123 Vlissides, John, 1, 172 volatile keyword, 65 JOIN THE APRESS FORUMS AND BE PART OF OUR COMMUNITY. You'll find discussions that cover topics of interest to IT professionals, programmers, and enthusiasts just like you. If you post a query to one of our forums, you can expect that some of the best minds in the business-especially Apress authors, who all write with The Expert's Voice™-will chime in to help you. Why not aim to become one of our most valuable partic• ipants (MVPs) and win cool stuff? Here's a sampling of what you'll find:

DATABASES PROGRAMMING/BUSINESS Data drives everything. Unfortunately, it is. Share informa~on, exchange ideas, and discuss any database Talk about the Apress line of books that cover software programming or administration issues. methodology, best practices, and how programmers interact with the 'suits.'

INTERNET TECHNOLOGIES AND NETWORKING WEB DEVELOPMENT/DESIGN Try living without plumbing (and eventually 1Pv6). Ugly doesn't cut it anymore, and CGI is absurd. Talk about networking topics including protocols, design, Help is in sight for your site. Find design solutions for your administra~on, wireless, wired, storage, backup, certifications, projects and get ideas for building an interactive Web site. trends, and new technologies.

JAVA SECURITY We've come a long way from the old Oak tree. Lots of bad guys out there-the good guys need help. Hang out and discuss Java in whatever fiavor you choose: Discuss computer and network security issues here. Just don't let J2SE, J2EE, J2ME, Jakarta, and so on. anyone else know the answers!

MAC OSX TECHNOLOGY IN ACTION All about the Zen of OS X. Cool things. Fun things. OS X is both the present and the future for Mac apps. Make Its after hours. It's time to play. Whether you're into LEGQ® suggestions, offer up ideas, or boast about your new hardware. MINDSTORMS™ or turning an old PC into a DVR, this is where technology turns into fun.

OPEN SOURCE WINDOWS is good; understanding (open) source is better. No defenestration here. Discuss open source technologies and related topics such as Ask questions about all aspects of Windows programming, get PHP, MySQL, Linux, , Apache, Python, and more. help on Microsoft technologies covered in Apress books, or provide feedback on any Apress Windows book.

HOW TO PARTICIPATE: Go to the Apress Forums site at http://forums.apress.com/. Click the New User link.