0% found this document useful (0 votes)
89 views42 pages

Compiled From Various Material By: Feng Wei

The document discusses various object-oriented design patterns such as delegation, interface, immutable, marker, proxy, factory method, abstract factory, builder, prototype, and singleton, providing examples and class diagrams for each pattern. It also covers initialization, filtering, composition, and other patterns for adapting, bridging, caching, and managing responsibilities, commands, states, and behaviors in an object-oriented program. The design patterns provide reusable solutions to common problems that arise during software design.

Uploaded by

John Conors
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views42 pages

Compiled From Various Material By: Feng Wei

The document discusses various object-oriented design patterns such as delegation, interface, immutable, marker, proxy, factory method, abstract factory, builder, prototype, and singleton, providing examples and class diagrams for each pattern. It also covers initialization, filtering, composition, and other patterns for adapting, bridging, caching, and managing responsibilities, commands, states, and behaviors in an object-oriented program. The design patterns provide reusable solutions to common problems that arise during software design.

Uploaded by

John Conors
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42



− Compiled from various material by Feng Wei


 

  

 
   
 
       


 
  
 
     

        


   

     
 
   

             ! " # # $  

by James O. Coplien
Bell Laboratories
Naperville, Illinois

1
Table of Contents

Delegation …………………………………………………………………………. 3
Interface …………………………………………………………………………… 3
Immutable ………………………………………………………………………… 4
Marker ……………………………………………………………………………. 4
Proxy ………………………………………………………………………………. 5

Factory Method …………………………………………………………………… 6


Abstract Factory …………………………………………………………………. 7
Builder ……………………………………………………………………………. 8
Prototype …………………………………………………………………………. 9
Singleton ………………………………………………………………………….. 9
ObjectPool ……………………………………………………………………….. 10

Layered Initialization ……………………………………………………………. 11


Filter …………………………………………………………………………….… 12
Composite ………………………………………………………………………… 13

Adapter …………………………………………………………………………… 14
Iterator …………………………………………………………………………… 15
Bridge ……………………………………………………………………………. 16
Façade ………………………………………………………………………….… 17
Flyweight ………………………………………………………………………… 18
Dynamic Linkage ……………………………………………………………….. 19
Virtual Proxy ……………………………………………………………………. 20
Decorator ………………………………………………………………………... 21
Cache Management …………………………………………………………….. 22

Chain of Responsibility ………………………………………………………… 23


Command ……………………………………………………………………….. 24
Little Language …………………………………………………………………. 25
Mediator ………………………………………………………………………… 26
Snapshot ………………………………………………………………………… 27
Observer ………………………………………………………………………… 28
State …………………………………………………………………………….. 28
Null Object ……………………………………………………………………… 30
Strategy …………………………………………………………………………. 31
Template Method ………………………………………………………………. 32
Visitor …………………………………………………………………………… 33

Single Threaded Execution ……………………………………………………. 35


Guarded Suspension …………………………………………………………… 36
Balking ………………………………………………………………………….. 37
Scheduler ……………………………………………………………………….. 38
Read/Write Lock ………………………………………………………………. 40
Producer-Consumer …………………………………………………………… 41
Two-Phase Termination ………………………………………………………. 42
2
       


Origin: Grand 98


Reason: An object needes to be different subclasses at different times.
Extend a class C by writing an additional class D with added funtionality that uses
Synopsis:
instances of C. 
An airline reservation system has roles such as flight crew, passenger, ticket agent,etc.
Example: A person can play different roles at different times, and more than one role at a time.
Inheritance makes this impossible. 
UML
1 Uses 1
Class Delegator
user usee
Delegate
Diagram:
Delegator Uses Delegate. Flight crew, Passenger, etc.
Solution: Delegate Specializes DelegateIF to a specific role. Person
DelegatorIF Base class or interface of all Delegators. Role


Note: The example has two layers of delegation: Role to Person and PersonWithRole to Role. 
Java API
It is the basis for Java’s delegation event model.
Usage:
See also: Bridge, Decorator, Facade, Proxy


     

Origin: Grand 98


Reason: A class needs to be independent of services provided by another class.
Abstract a class C by writing an interface IF. Clients access class C through
Synopsis:
interface IF. 
A business application uses an Address class in a variety of objects, e.g., Vendors,
Example: Clients, Freight companies, etc. To make these objects less dependent of the
details of the Address class, the objects should rather use an interface, AddressIF. 
UML Class Client  uses
1
<<interface>>
IndirectionIF
implements Service
Diagram:

A class that provides data and/or methods to the


Service Address
Client.
Solution: Vendor, Client,
Client A class that uses the services of class Service.
etc.
ServiceIF Interface of class Service. AddressIF


Java API Ex: Java.io.FilenameFilter is an interface to tell if a named file is included a


Usage: collection.

3
        

Origin: Grand 98


Reason: An object's state should never change.
Set the state of an object at construction time. Do not define non-final variables or
Synopsis:
state-changing methods. 
An application deals with the positions of objects. Positions are not allowed to
Example:
change. When an object moves, a new position for the object is constructed. 
There are no specific classes. Constructors set all the state variables (the
Solution:
coordinates of a position). 
See also: Singleton
Java API
Instances of String class are immutable.
Usage:

    

Origin: Grand 98 (but there are many earlier examples in the Java APIs)
Reason: A class needs a semantic attribute, but no specific members.
Synopsis: Define an empty interface, M. Say that a class implements interface M. 
How can one mark a class, C, whose objects are equal only if they are the same
Example:
object (and, thus, use == instead of equals for comparison). 
<<interface>> Unmarked
Recognizes MarkerIF

UML Class
Diagram
Utility

Operation1(:Object) Marked

Solution: Marker An interface (trivially) implemented by class C. e.g., 


   .


Java API
Java API interfaces java.io.Serializable and java.rmi.Remote for classic examples. 
Usage:

4
   

Origin: unknown
It is incovenient to access a service for a variety of reasons, e.g., the object
Reason: providing the service is quite complex, or may not exist at the time the service is
requested (and so it must be created). 
Access an object's services indirectly through another object, the proxy. Clients are
Synopsis:
generally unaware of the proxy's existence. 
A hashtable is expensive to clone. Reading into a cloned hashtable gives the same
results as reading into the original, until the original is modified. Cloning can be
Example:
delayed until the cloned hashtable is to become different from the original
hashtable. 
AbstractService <<interface>>
ServiceIF
doIt( )
... doIt( )
...

UML Class
Diagram:
ServiceProxy Service
ServiceProxy Service
doIt( ) doIt( )
doIt( ) doIt( )

ServiceClass The class providing services. Hashtable


The class through which the ServiceClass
Proxy 
Solution: services are accessed.
Common interface of both ServiceClass and say,
ServiceIF
Proxy. HashtableIF


See also: Bridge, Decorator, Delegation, Facade


Access proxy: Enforces security policies to access a service object.
Variations: Remote proxy: Hides that a service object is on a remote machine.
Virtual proxy: Creates perception that a service object exists when it might not.


5
          

Origin: GoF 95


Provide an interface for creating an object, but let subclasses decide which class to
Reason:
instantiate (aka virtual constructor). 
An abstract class, the FactoryMethod, defines abstract or near-empty methods that
Synopsis: return product components and a final creator method to create an entire product.
Subclasses override methods that return product components but use the same creator. 
An office productivity program manages two classes: Document, e.g., texts, images,
Example: sounds, etc., and Application to create or open documents. The Application class does
not know which specific Document class to instantiate. 
Product
*  1
CreationRequestor
operation1 Uses
newDocument
operation2
...
...
 1 requestor
* Requests-creation
creator
*
UML <<interface>>
Class FactoryIF
ConcreteProduct
Diagram: createProduct(discriminator):Product
operation1
operation2
...

Factory
 Creates 1
createProduct(discriminator):Product

Interface of objects the factory


Product Abstract document
method creates.
Implements Product for a specific Text or image or sound,
ConcreteProduct
document. etc., document.
Application-independent class that
Creation
creates (indirectly via a factory 
Solution: Requestor
class) application-specific objects. 
Declares the factory method that
Factory IF 
returns a Product. 
Application-specific class with
DocumentFactory,
Factory Class method to create Concrete Products.
ImageFactory
Implements Factory IF. 


Java API The Java API uses the Factory Method pattern to allow the integration of the applet
Usage: environment with its host program.
AbstractFactory, Builder, Prototype
See also:
creational pattern summary
All the concrete product classes are known in advance.
Special:
There is a variable or large number of product classes.

6
            

Origin: GoF 95


Provide an interface for creating families of related or dependent objects without
Reason:
specifying their concrete classes (aka Kit). 
An interface, the abstract factory, defines abstract methods that return product
Synopsis: components. A creator uses a different concrete factory per family of products.
Different objects are created by different virtual methods of the concrete factory. 
A graphical toolkit needs to support multiple look-and-feels. Applications cannot
Example: hardcode widgets for a particular look-and-feel or they would be too difficult to
change for another look-and-feel. 
AbstractFactory 
Uses Client
getFactory
createA  1 1
Uses
createB
WidgetA
... *

Product2WidgetA Product1WidgetA
ConcreteFactory2
UML Class 1 Creates  * *
createA
Diagram: createB
...
Creates 
1
ConcreteFactory1
1

Uses
createA
createB WidgetB
... *
1
 Creates

* Product1WidgetB Product2WidgetB
Creates 
*

AbstractProduct Interface for a type of product object. Button, Scrollbar.


Implements AbstractProduct for a
MotifButton,
ConcreteProduct specific widget to be created by the
MotifScrollbar.
corresponding ConcreteFactory. 
Interface for operations that create
AbstractFactory say, WidgetFactory
Solution: abstract products.
Implements the operations of say,
ConcreteFactory
AbstractFactory. MotifWidgetFactory.
Uses only methods of
Client AbstractFactory and 

AbstractProduct. 


Java API Usage: Java API uses this pattern to implement the Java.awt.Toolkit class.
See also: Builder, FactoryMethod, Prototype, creational pattern summary

7
      

Origin: GoF 95


Allow a client to construct a complex object, the product, by specifying only its type
Reason:
and content. 
An interface or abstract class, the AbstractBuilder, defines a static method, getInstance
Synopsis: that takes the product type and return a Concrete Builder. A Director calls methods of
the Concrete Builder to build the product. 
An e-mail gateway transforms messages received in MIME format to specific formats
Example:
for different e-mail systems. A message is composed of many parts/fields. 
Uses 

1
1
Request-creation-of-ConcreteBuilder 
Client
requestor
1 requestor creator 1..*

AbstractBuilder
 Request-direction-of-build
getInstance( ):AbstractBuilder
0..*
UML buildPart1( )
1 buildPart2( ) <<interface>>
Class
Diagram: Uses  ...
getProduct( ):ProductIF
ProoductIF

1 director 1

Director

Build(:Builder):ProductIF ConcreteBuilder

buildPart1( ) 1
Creates  1
Product
buildPart2( )
...
getProduct( ):ProductIF

has methods "To",


AbstractBuilder Interface for building product objects.
"From", etc..
Implements AbstractBuilder for a specific say, UnixBuilder,
ConcreteBuilder
e-mail system. Win95Builder
Calls methods of AbstractBuilder to
Director 
transform a message.
Solution:
Calls method getInstance of
Client AbstractBuilder. 

Passes result to Director to get the product. 


Object under construction, subparts are
Product included. ConcreteBuilder sets 

representation and construction. 




AbstractFactory, FactoryMethod, Prototype, creational pattern summary


See also:


8
      

Origin: GoF 95


Create customized objects, the products, without knowing their exact classes or
Reason:
construction details. 
A class, the Client, stores an instance, the Prototype, of every product it may create.
Synopsis:
A method of the Client registers prototypical instances. 
A CAD program allows users to draw symbols from a palette. It must be easy to
Example:
provide additional symbols. 
<<interface>>
PrototypeBuilder Cloneable

creator
*
Create-and-register-prototype-objects
UML
Class
registrar 1
Diagram:
Client
Uses
Prototype
registerPrototype 1 1..*
...

Interface implemented by all the symbols of CAD


PrototypeIF
products. program
Solution: Implements the PrototypeIF interface
Prototype 
and is cloned.
PrototypeBuilder Supplies prototypical objects. 


Java API
The Prototype pattern is the very essence of JavaBeans.
Usage:
AbstractFactory, FactoryMethod, Builder, creational pattern summary
See also:


 
   


Origin: Gof 95


Reason: Ensure that only one instance of a certain class is created.
Define a class with a private constructor and a public static getInstance method
Synopsis:
that always return the same instance. 
Example: An applet class that ensures that no more than an audioclip is played at a time. 
Solution: Singleton A class of which there is at most one instance. 


Java API The Java API class java.lang.Runtime is a singleton class. It has exactly one
Usage: instance.
See also: Immutable

9
       

Origin: Grand 98


Reason: Allows clients to re-use objects rather than to discard and later re-create them. 
Define a wrapper class, the Object Pool, around the construction of reusable
Synopsis: objects. The class accepts from clients returned used objects and returns them to
clients instead of new objects. 
Database connections may be expensive to create. An Object Pool stores used
Example: connections when no longer needed and returns them when a new connection is
required. 
0..* Manage-Reusable-Objects
Client
client
manager 1
1
ReusablePool

<<constructor>>
-ReusablePool
UML Class Uses ! <<misc>>
+getInstance()
Diagram: +accquireReusable():Reusable
+releaseReusable(:Reusable)
+setMaxPoolSize(maxSize:int)
...

* 1

0..*
Reusable

Class of the reusable objects managed by the Database


Reusable
ReusablePool. connection
Solution:
Client Class that uses the Reusable objects. Database client
ReusablePool Class that manages the Reusable objects. 


See also: CacheManagement


An ObjectPool object is generally a Singleton and manages one type only of
Note:
objects. 

10
!      
      "   


Origin: Grand 98


Reason: The logic to select which of many classes to instantiate is common to all the classes. 
Encapsulate common and specialized logic to create objects when common logic is
Synopsis:
used to select the class of the objects to create. 
Create a database query object whose class depends on the specific database been
Example: queried. The creation executes a common piece of code that determines which class to
instantiate. 
<<interface>>
1
" Service
ServiceImplFactoryIF Requests-creation 1
requestee requestor
setFactory(:ServiceImplFactoryIF)
createSerivceImpl

ServiceImplFactory

createServiceImpl

UML 1
Creates #
class
diagram: Uses #
* * *
ServiceImpl1 ServiceImpl2 ...

<<interface>>
ServiceImplIF

The class that manages the creation of the


Service objects that implement ServiceImplIF. The 

only visible class of the pattern. 


Interface or abstract class of the objects
ServiceImplIF QueryIF
Solution: created by Service. 
Concrete classes implementing OracleQuery
ServiceImpli
ServiceImplIF. SybaseQuery
The class that creates the objects that
ServiceImplFactory 
implement ServiceImplIF. 


Java API
The java.net.URL class uses the Layered Initialization pattern.
Usage:
See also: The creational patterns 

11
     

Origin: BMRSS 96


Reason: Perform composable transformations and computations on streams. 
Define a composable interface common to all transformations and computations.
Synopsis:
Make implementations of the interface independent of their contexts. 
Example: A class that counts the number of bytes and/or lines of a stream. 
AbstractSourceFilter

<<constructor>>
AbstractSink AbstractSource
create(AbstractSource)<<m
isc>> getData( )
1 1
getData()
...
%
$ Gets-data-from
Gets-data-from
UML class
diagram: ConcreteSourceFilter

1 <<constructor>> 1
create(AbstractSource)
<<misc>> ConcreteSource
getData()
... getData( )

Source Filter

There is both an interface and one or more concrete classes that


Source
abstract a stream that produces data. Has method to get data. 
There is both an interface and one or more concrete classes that
SourceFilter abstract filtering a Source. Has method to set the source and get
Solution: data. 
There is both an interface and one or more concrete classes that
SinkFilter
abstract filtering a Sink. Has method to set the sink and put data. 
There is both an interface and one or more concrete classes that
Sink
abstract a stream that consumes data. Has method to put data.


Java API The java.io.FilterReader class (abstract source filter);


Usage: The java.io.FilterWriter class (abstract sink filter).
See also: Decorator 
Producer puts data to SinkFilter that puts data to Sink.
Alternatives:
Consumer gets data from SourceFilter that gets data from Source. 

12
#       

Origin: GoF 95


Reason: A structured object is recursively defined in terms of other objects. 
Define an interface common to a family of objects. Build objects in a tree-like
Synopsis:
structure whose nodes are objects of the family. 
A document is made by elements such as pages, lines, etc., and embedded or nested
Example:
documents. 
AbstractComponent

operation( ) *

ConcreteComponent1 ConcreteComponent2 ... AbstractComposite

operation( ) operation( ) operation( )


UML add(AbstractComponent)
Class remove(AbstractComonent)
getChild(int)
Diagram:

ConcreteComposite1 ConcreteComposite2 ...


operation( ) operation( )
add(AbstractComponent) add(AbstractComponent)
remove(AbstractComonent) remove(AbstractComonent)
getChild(int) getChild(int)

Superclass of the entire family of


AbstractComponent DocumentElement
objects in the composite structure. 
Implementations of
ConcreteComponent AbstractComponent, the leaves of the Page, Line
tree-like structure. 
Solution:
Superclass of the properly composite
AbstractComposite Document
objects in the composite structure. 
Implementations of
WordDocument,
ConcreteComposite AbstractComposite, the branches of
Spreadsheet
the tree-like structure. 


The java.awt.swing package contains a good example of the Composite pattern.


AbstractComponent : Component
Java API
AbstractComposite : Container
Usage:
ConcreteComponent: Label, TextField and Button.
ConcreteComposite : Panel, Frame and Dialog.
See also: Visitor 

13
      

Origin: GoF 95


A client needs the service of an object, Obj, through an interface, IF, but Obj does
Reason:
not implement IF. 
Define a class, the Adapter, that implements interface IF and provides the service
Synopsis:
via Obj. 
A method copies arrays filtering out some elements. The criterion to filter out an
Example: element is defined by an interface, CopyFilterIF. Array elements that have the
information for the filtering criterion may not implement CopyFilterIF. 
<<interface>>
Client Uses ' TargetIF
1..* 1
interfaceMethod( )
UML
Class
Diagram: Adaptee &
Uses
Adapter
... 1 1
otherMethod( )
interfaceMethod( )

Client Class that needs a service through interface TargetIF.


TargetIF Interface expected by Client to obtain a service.
Solution: Class that implements TargetIF and provides the service using
Adapter
Adaptee. 
Adaptee Class that does not implement TargetIF and provides the service. 


Java API The java.awt.event.WindowAdaptor class (intended to be subclassed rather than used
Usage: directly).
Proxy
See also:
Facade

14
    

Origin: GoF 95


To sequentially access all the objects of a collection without exposing the
Reason:
collection's interface and/or representation. 
Define an interface with methods to produce a sequence of objects. Make the
Synopsis:
interface independent of the object's container. 
An InventoryBrowser displays InventoryItems encapsulated in an
Example: InventoryCollection. The InventoryBrowser does not access the InventoryCollection,
but an object that implements the InventoryIterator interface. 
<<interface>> <<interface>>
CollectionIF
Creates ' InteratorIF

iterator( ) : IteratorIF( ) hasNextItem( ) : boolean


... getNextItem( ) : InventoryItem
UML
Class
Diagram:

&
Collection Fetches-objects-from Iterator

Collection Class that encapsulates a collection of objects.


Interface that defines the methods to sequentially access the objects
IteratorIF
in a Collection. 
Solution:
Iterator Implementation of IteratorIF.
Common interface to Collections. Provides method(s) to create
CollectionIF
Iterators. 


The collection classes in the java.util package follow the Iterator pattern.
Java API
The java.util.Collection interface plays the CollectionIF role.
Usage:
The java.util.Iterator interface plays the IteratorIF role.
See also: Adapter (Iterator is a specialized Adapter)

15
     

Origin: GoF 95


Allow (a hierarchy of) abstractions to vary independently of (a hierarchy of) their
Reason: implementations. E.g., select or switch an abstraction's implementation at run-time
(a.k.a Handle/Body). 
Decouple an abstraction from its implementation so that the two can vary independently
Synopsis:
[GoF]. 
A windowing system defines a Window and some specializations, e.g., IconWindow.
Example:
These abstractions are implemented for various platforms, e.g., Unix, Apple, Microsoft. 
<<interface>> Impl2
Abstraction
1 Uses ' 1 AbstractionImpl
operation( ) Impl1
operation( )

UML
Class
Diagram:
<<interface>> SpecializedImpl1
SpecializedAbstraction
Uses ' SpecializedAbstractionImpl
specializedOperation( ) 1 1
specializedOperation( ) SpecializedImpl2

Defines the abstraction. Keeps a reference to an object of


Abstraction
type Implementor.

Solution: RefinedAbstraction Extends the interface defined by Abstraction.


Implementor Defines the interface for implementation classes.
ConcreteImplementor Implements the Implementor.


Adapter (applied after coding, whereas Bridge is applied in design)


See also:
Delegation

16
      

Origin: GoF 95 (also called dispatcher/supervisor)


Reason: Access a set of related objects through a single object or interface. 
Define a class, the Facade, that accesses a set of related objects. Allow clients to
Synopsis:
access the set of related objects only through the Facade. 
Mail messages have components such as Body, Header, Sender, etc. Define a class
Example: MessageCreator that deals with the above components. Clients that create mail
messages interact with MessageCreator only. 
Client

$ Uses
1

*
Facade

UML
Class
Diagram

Facade Class that accesses Relatedi. MessageCreator


Body, Header,
Relatedi Group of related objects that provide a service.
Solution: etc.
Class that accesses Facade to get the services of
Client 
Relatedi.


Java API
The java.net.URL is an example of the Façade pattern.
Usage:
Interface
See also: Proxy
Adapter

17
   $      

Origin: GoF 95


Reason: Many instances of a class, the Client, contain the same information. 
Define a class, the Flyweight. One instance of this class is shared by many instances of
Synopsis:
Client. 
A wordprocessor represents glyphs by character code, font, size, color, etc. A paragraph
Example:
should share equal gliphs, not duplicate them. 

1
1 AbstractFlyweight
Client
1
$ operation(extrinsicState:object)
Uses
Uses
$ Uses
$
UML
Class Creates and Manages Reuse of 4
Diagram 1 0..* 0..* 0..*

FlyweightFactory SharedConcreteFlywieght UnsharedConcreteFlywieght

getFlywieght(attribute:object) operation(extrinsicState:object) operation(extrinsicState:object)

1
Creates ' 0..*

Superclass or interface of all


AbstractFlyweight glyph
Flyweight objects.
context
Class of sharable flyweight
SharedConcreteFlyweight independent
objects. Stores intrinsic state.
characters
Solution: Class of unsharable flyweight context dependent
UnsharedConcreteFlyweight
objects. Stores extrinsic state. characters
FlyweightFactory Manager of the flyweight objects. 

References a flyweight objects.


paragraph or
Client Computes or stores extrinsic
document
state.


Java uses the Flyweight pattern to manage String objects used to represent string literals.
Java API If there is more than one string literal in a program that consists of the same sequence of
Usage: characters, a Java virtual machine uses the same String object to represent all of those
string literals.
Composite (used in conjunction with flyweight objects)
See also: FactoryMethod (to build objects flyweight objects)
Immutable (implemented by flyweight objects)

18
 
    ! 
    

Origin: Grand 98


Decide at run-time which particular class, implementing a specified interface, to
Reason:
load and use. 
Synopsis: Use Java's URLClassloader or Class classes to load a class on demand. 
A food processor with a very large number of programs loads these programs
Example:
dynamically from a mass storage device. 
&
uses
1 1
<<interface>> AbstractLoadableClass
EnvironmentIF
setEnvironment(:EnvironementIF)
operation1( ) start( )
operation2( ) ...
UML Class ...
Diagram: 1

uses '

Environment ConcreteLoadableClass

There is both an interface and a concrete class. It load the


Environment LoadableClass which in turn may call methods of the
Solution: Environment. 
There is both an interface and one or more concrete classes. It
LoadableClass
has methods to set the Environment and start the execution. 


Java API
Web browsers use the Dynamic Linkage pattern to run applets.
Usage:
VirtualProxy (to hide that loading is dynamic)
See also:
AbstractFactory (for the selection of the concrete loadable class) 

19
%         

Origin: Larman 98


Delay the instantiation of an object (expensive to instantiated) until the object is
Reason:
needed. 
Create an object, the VirtualProxy, that allows clients indirect access to the expensive-
Synopsis:
to-create object, and hides from clients whether the expensive-to-create object exists. 
A large applet executes several well-separated components. A typical execution of the
Example:
applet requires some, but not all, these components. 
Uses ' 1 <<interface>>
ServiceIF

operation1( )
operation2( )
... ServiceHelper1

UML Client 1 *
Class Uses '
ServiceProxy
Diagram: 1..* 1
1 operation1( )
Uses ' operation2( ) 1 Creates ' Service ServiceHelper2
... 1
operation1( ) *
operation2( ) 1 Uses '
...

Class that needs the services of the Service class. The Client does
Client not access the Service class directly, thus it is insensitive to whether
the Service class is loaded. 
Class providing services to the Client. Supposedly, the Service class
Service
Solution: is expensive to load and/or instantiate. 
Interface implemented by both the Service and the ServiceProxy
ServiceIF
classes. 
Class that provides services to the Client through the Service class.
ServiceProxy
It loads and/or instantiates this class only when needed. 


Proxy (a generalization of this pattern)


See also:
DynamicLinkage (option for dynamically loading a class) 

20
     

Origin: GoF 95


Extend the functionality of an instance of a class, but not of all instances of the
Reason:
class. 
Define a class, the Decorator, that encloses the object whose functionality is to be
Synopsis:
extended. 
Consider a security and monitoring system. When the object controlling a door
receives a request to open a door, the monitor controlling the door displays the
Example:
doorway. There are several classes for opening a door and several classes for
displaying a doorway. 
AbstractService
1
Operation1( )
Operation2( )
... % Extends

ConcreteService AbstractWrapper
UML Class Operation( ) Operation( )
Diagram: Operation2( ) Operation2( )
... ...

ConcreteWrapperA ConcreteWrapperB

Operation( ) Operation( )
Operation2( ) Operation2( )
... ...

There is both an interface and one or more concrete Doorway


Service
classes. Objects of these classes provide a service.  monitor
Solution: There is both an interface and one or more concrete
Wrapper classes. Objects of these classes delegate operations to Door opener
Service. 


See also: Delegation (the Decorator pattern uses delegation)

21
#      
    
 

Origin: Grand 98


Reason: Allow fast or efficient access to objects that are slow or expensive to obtain. 
Retain for later access a reference to a slow or expensive to obtain object once it has
Synopsis:
been constructed. 
A program allows users to retrieve information about a product. The information
Example:
about the product comes from a variety of sources that are slow to access. 
1 1
Cache
CacheManager
Cache-objects-for (
fetchObject(:ObjectKey) addObject( :Object )
fetchObject( :ObjectKey )
1 cacher
1
UML Class Create-objects-for-caching
Diagram: ObjectKey Caches )
1 fetcher
ObjectCreater 0..*

creatObject(:ObjectKey) Object

Product
ObjectKey Identifies an object to be fetched from the Cache. 
ID
Objects are stored into and retrieved from the Cache
CacheManager 
by this class. 
Solution:
Class(es) responsible for creating objects not in the
ObjectCreator 
Cache. 
Container for cached objects. Has methods to insert,
Cache 
retrieve, and remove objects. 


See also: ObjectPool (a CacheManagement without IDs)

22
#   
 &   
        

Origin: GoF 95


To issue a command to an object that may execute it or send it to another object for
Reason:
execution. 
Different commands are executed by different objects in a chain. Objects early in the
Synopsis:
chain pass on commands they should not execute. 
Consider a security system. In a system with only a few sensors, an alarm is handled
Example: locally, e.g., ring a bell. In a large system, an alarm is reported to a remote control
station. 
( Send-command-to-next-handler-in-chain
CommandSender
1 predecessor
sender 1

Send-command (
CommandHandler
1 successor
postCommand( ) 1
UML receiver handleCommand( ):boolean
Class
Diagram:

ConcreteCommandHandler1 ConcreteCommandHandler2

handleCommand( ):boolean handleCommand( ):boolean

Calls postCommand of the first object in the chain.


CommandSender
It is the client of the chain. 
Superclass of all the ConcreteCommandHandlers in
a chain of responsibility. Defines methods
postCommand that manages the chaining of
Solution: CommandHandler
commands, and handleCommand that returns
whether a command was completely executed. Has
link to next CommandHandler in the chain. 
These classes override handleCommand, but not
ConcreteCommandHandleri
postCommand. 


Composite (the chain is a composite object)


See also:
Command (may use it for representing commands)

23
#   
 

Origin: GoF 95


Reason: To allow operations on commands such as sequencing and undoing. 
Represent commands as encapsulated objects. Provide a command manager to
Synopsis:
execute commands. 
A word processing program should be able to undo and redo previously executed
Example:
commands. 
AbstractCommand +
Manages
doIt( )
Invoker undoIt( ) 0..*

1
1 creator/invoker
UML Class
Diagram: CommandManager

Creates-and-invokes *
ConcreteCommand
0..*
invokee doIt( )
undoIt( )

Interface for executing a command. Has abstract methods


AbstractCommand
such as doit and undoit. 
Implement a specific command. Constructor has required
ConcretCommand
Solution: parameters. Specializes doit and undoit methods. 
Invoker Asks a command to do its job. May create the command. 
Manages a collection of commands to support "history"
CommandManager
requests. Can be quite general. 


Snapshot (coarser alternative to undo)


See also:
Little Language (may use this pattern)

24
!      ! 
     

Origin: Grand 98 (see also Interpreter Gof 95)


Reason: To provide text-based interaction with a program. 
Synopsis: Parse, compile, and/or interpret a formal language. 
To search records in a data structure keywords that occur in a record are combined
Example:
by logical connectives such as and, not, etc. 
AbstractNonterminal
1 1..*
Client
Executes * execute( )

ConcreteNonterminal1 ConcreteNonterminal2 ...


*
execute( ) execute( )
, Creates
, Creates
,
* Creates *
UML Class 1 1
1
Diagram: Parser

parse(input:InputStream):AbstractNonterminal

, Read-tokens
1 token consumer

token source InputStream


1
LexicalAnalyzer character source *
create(input:inputStream)
+
1 Read-characters
nextToken( ) : TerminalToken character consumer

The class or set of classes that produces a stream of Tokens from the
Lexer
source code. 
Parser The class or set of classes that builds the AST from the stream of Tokens. 
Solution: An abstract class and a set of concrete classes that provide an internal
Token
representation of the lexical components of the source code. 
An abstract class and a set of concrete classes that provide an internal
AST
representation of the structure of the source code. 


Java API
Subclasses of java.text.Format use the Little Language pattern.
Usage:
Composite (an AST is often a Composite object)
See also:
Visitor (used to process the AST)

25
      

Origin: GoF 95


Reason: To coordinate the change of state of several objects. 
Place the logic to change the state of all the objects in a separate object, the
Synopsis:
Mediator. 
A dialog box receives information to plan and reserve a banquet. Several objects
Example: contribute to this process. Changing the state of one object affects the state of other
objects. 
Colleague2
Colleague1
addEventListener2(:EventListener2)
1 addEventListener1(:EventListener1) addEventListener3(:EventListener3)
1
... ...

Notifies of state Notifies of state - Notifies of state


changes - changes - changes

<<interface>> <<interface>> <<interface>>


EventListener1 EventListener2 EventListener3
UML
Class
Diagram:
, Propagates Changes
,
Propagates Changes
Mediator

registerColleague1(Colleague1)
1 1
registerColleague2(Colleague2)
...
handleEvent1( )
handleEvent2( )
...

A set of heterogeneous classes whose states affect each other


Colleagues
behaviors. 
Classes that make Colleagues unaware of the Mediator. A
Solution: EventListeners Colleague tells its EventListener of a change of state; the
EventListener tells the Mediator. 
Class that implements the logic to execute when a Colleague
Mediator
changes state. 


Java API
Usage:
Adapter (used by the Mediator to receive event notifications)
See also: Interface (used to keep the Colleagues independent of the Mediator)
Observer (alternative to the Mediator)

26

     

Origin: Grand 98 (see also Memento, GoF 95)


Reason: To capture and later restore the state of an object.
Define an object responsible for capturing and restoring the state of objects. These
Synopsis:
objects should implement a common interface. 
Example: A player would like to play a long game in short temporally-separated intervals. 
Originator
declaring class
Caretaker createMemento( ):MementoIF
setMemento(:MementoIF)
1
1 , Is-a-Private-Member-Class-of

Creates -
0..* 0..*
<<interface>> <<interface>>
MementorIF Memento member class

UML Figure 1 - Snapshot using memento objects


Class
Diagram: +
Serializes 1
ObjectOutputStream
1 Writes Bytes * 1
OutputStream
serializer byte
consumer
1 object

Target

1 object

1
+ 1
+ 1
Deserializes Read-bytes
ObjectInputStream InputStream
deserializer byte byte
consumer producer

Figure 2 - Snapshot using serialization


Originator An object of this class can have its state saved and restored. 
Interface to access Memento objects. Must protect the encapsulation
MementoIF
of the Originator's state. 
Solution: Private static class of Originator which implements the MementoIF
Memento
interface. 
Maintains one or more Memento objects. May hold them in memory
Caretaker
or store them on disk. 


Java API
Usage:
See also: Command (similarly, it allows state changes to be undone)

27
    '  

Origin: GoF 95


To establish dependencies between objects so that when one object changes state, its
Reason:
dependent objects are informed. 
Define and implement interfaces with methods to register dependencies between
Synopsis:
objects and to notify dependent objects of state changes. 
In a security system objects that trigger alarms must notify objects that handle alarms,
Example:
but at the same time they must be largely independent of each other. 
<<interface>> Registers-to-receive-notifications * <<interface>>
ObserverIF 0..* 1 ObservableIF

notify addObserver(:ObserverIF)
0..* removeObserver(:ObserverIF)

Observer
UML
,
Observable
Diagram: Notifies
1 1

Register-observers - - Notifies

1 1

Multicaster

addObserver(:ObserverIF)
removeObserver(:ObserverIF)

There are both an interface and one or more implementing classes.


Observer The interface has an update method called by Observable objects
when their state changes. 
There are both an interface and one or more implementing classes.
Solution:
Observable The interface has methods to add and remove Observer objects
whose update method is called upon a state change. 
This class manages the registration of Observers on behalf of
Multicaster
Observables. 


Java API
Java’s delegation event model is a specialized form of the Observer pattern.
Usage:
Delegation (Observables delegate functionality to Observers)
See also: Adapter (used by non-conformant Observables and/or Observers)
Mediator (used to coordinate multiple state changes of Observables)
Note: The version described in this page is known as Event Delegation Model. 

28
     

Origin: GoF 95


To allow an object to dynamically change a set of attributes. To change the nature (as
Reason:
opposed to the value) of an object's state. 
Synopsis: Encapsulate the state of one object as one of a set of objects with the same superclass. 
A dialog box in a GUI may have different buttons at different times. The behavior of
Example:
a same button may radically change over time. 
ContextState

+event1 : int = 1 {frozen}


Context Uses * +event2 : int = 2 {frozen}
...
-currentState : State #state1 : ConcreteState1
#state2 : ConcreteState2
... ...

+operation1( )
+operation2( )
...
#enter( )
UML +start( ) : State
+processEvent(event:int) : State
Diagram:

ConcreteState1 ConcreteState2 ...


+operation1( ) +operation1( )
+operation2( ) +operation2( )
... ...
processEvent(even t: int) : State processEvent(even t: int) : State

Class whose instances exhibit stateful behavior. It keeps a


Context reference to a ConcreteState object that implements the state
functionality. It is the client of the State pattern. 
Solution:
Superclass of all classes used by Context to represent a state. It
ContextState
provides methods for state initialization and change. 
ConcreteStatei Concrete subclass of ContextState. It is referenced by Context. 


Delegation (the state functionality of an object is delegated to another object)


See also:
Flyweight and Singleton (to implement shared or unique-instance states)

29


(         

Origin: Woolf 97


To represent a null reference (a non-existent object) with an (existing) object to
Reason:
avoid handling special cases. 
Define a special class generally with no state, but the same methods expected in the
Synopsis:
object that the Null Object stands for. 
Objects in a sequence have a reference to the next object. If the last object of the
Example: sequence has a null reference, a test is required before invoking a method of the
referenced object. A Null Object eliminates the need for a test. 
Delagator
Uses . AbstractOperation
1 1

UML Class
Diagram:

NullOperation RealOperation

This class delegates an operation to objects that normally


Delegator
may not exist. 
AbstractOperation Superclass or interface of the objects that may be null. 
Solution: Implements the operation that the Delegator delegates to
RealOperation
AbstractOperation. 
Implements a do-nothing operation that the Delegator
NullOperation
delegates to AbstractOperation. 


Singleton (the null object is often stateless)


See also:
Strategy (the Null Object pattern may ease the design of the Strategy pattern)

30


       

Origin: GoF 95


Reason: To allow the selection of an algorithm to vary by object and over time. 
Synopsis: Encapsulate related algorithms in classes that are subclasses of a common class. 
Consider a program that generates a calendar. Holidays displayed by the calendar
Example:
must vary by nation and/or religious group. 
Client Uses . AbsrtractStrategy
1 0..1
operation( )

UML
Class
Diagram:

...
ConcreteStrategy1 ConcreteStrategy2

This class delegates an operation to an


abstract class or interface, the
Client AbstractStrategy. It does not know the Calendar printer.
actual object that will execute the
operation. 
Defines method,
Abstract class or interface that abstracts
Solution: isHoliday, that
AbstractStrategy the operation provided by all its
takes a day of the
subclasses, the ConcreteStrategies. 
year.
Specilizes
There are many classes that provide
method isHoliday
ConcreteStrategyi different implementations of the
for a specific
operation specified by AbstractStrategy. 
country.


Java API The CheckInputStream and CheckOutputStream classes in the java.util.zip package
Usage: both use the Strategy pattern to compute checksums on byte streams.
See also: Template Method and Factory Method (structurally similar)

31
)             

Origin: GoF 95


To allow subclasses of a common class to vary portions or steps of a general
Reason:
algorithm. 
A general algorithm implemented by a base class calls abstract methods for some
Synopsis:
steps. Subclasses of the base class specialize these methods. 
Consider the process of logging in and authenticating a user for an application. Some
Example: steps of the process, e.g., prompting the user are application independent. Other
steps, e.g., authenticating the user, are application dependent. 
AbstractTemplate

templateMethod( )
...
#operation1
#operation2
...
UML
Diagram:

ConcreteTemplate

#operation1
#operation2

This class defines a method, the templateMethod, that


implements the general logic of an algorithm. The
AbstractTemplate
templateMethod calls other methods that are overriden by
Solution: ConcreteTemplate. 
This class overrides methods that are called by the
ConcreteTemplate
templateMethod. 


Strategy (modifies logic for individual objects rather than classes)


See also: Factory Method (specializes the construction of an object rather than the execution
of an algorithm)

32
%     

Origin: GoF 95


To define new operations on the objects of a structure (as in a Composite) without
Reason:
changing the objects. 
Each object, say obj, of the structure defines a method, conventionally called accept, that
Synopsis: takes an object conventially called a visitor. The visitor, rather than obj, implements the
new operation. Method accept dispatches the execution of the operation to the visitor. 
A document for word processing is a Composite whose nodes are paragraphs, lines,
images, etc. To create the table of content of a document one can define an operation in
Example:
each node class. The Visitor pattern allows one to define these operations in a separate,
dedicated object. 

1 Uses / 0..* ObjectStructure


Client
1 Uses / 1
1 1
0 Uses Uses / Contains 0
1 1

ConcreteVisitor1 ConcreteVisitor2
0..*
...
visit(:Element1) visit(:Element1)
AbstractElement
visit(:Element2) visit(:Element2)
... ... accept(:AbstractVisitor)
UML ...

Class 1
Diagram:
Uses

Visitor

visit(:Element1)
visit(:Element2) ConcreteElement1 ConcreteElement2 ...
...
accept(:AbstractVisitor) accept(:AbstractVisitor)
... ...

Ideal Visitor Pattern


Interface or superclass of all classes in a Composite structure.
AbstractElement
Defines an accept method that takes a Visitor. 
Class implementing AbstractElement and overriding the accept
ConcreteElementi
method. 
Solution: Interface or superclass of all classes that perform an operation on
Visitor the AbstractElement. Defines a family of visit methods each taking
a ConcreteElement. 

Concrete subclass of Visitor for a specific operation. Overrides all


ConcreteVisitori
the visit methods. 

33
An instance of this class is the object to be "visited". Most often is
ObjectStructure
a Composite. 


Composite (often the object to be visited)


See also:
Little Language (often uses visitors)
This is a complicated pattern that requires a good understanding of the concepts of
overloading and overriding. The following code sketches the key elements of this pattern.

Interface of all visitable objects.

interface Element { void accept (Visitor v); }

Visitable classes. The type of "this" is bound at compile time.

class Element_1 implements Element {


public void accept (Visitor v) { v.visit (this); }
}
...
class Element_n implements Element {
public void accept (Visitor v) { v.visit (this); }
}

Note: Interface of all visitors.

interface Visitor {
void visit (Element_1 e);
...
void visit (Element_n e);
}

Actual visitor class. Implements an operation that would otherwise be a member of each
Element_i.

class MyVisitor implements Visitor {


public void visit (Element_1 e) { ... }
...
public void visit (Element_n e) { ... }
}

Sometimes methods accept and visit take one extra argument, an Object, and return a
value, an Object. 

34
 
   )       *      


Origin: Grand 98


Reason: To prevent concurrent access to data or other resouces (aka Critical Section). 
Synchronize on a same object the portions of code that should not be
Synopsis:
concurrently executed. 
Several threads set and get a datum held by an object. The time of an access is
Example:
non deteministic. 
Resource

safeOp1
UML Class safeOp2
...
Diagram: unsafeOp1 {concurrency=guarded}
unsafeOp2 {concurrency=guarded}
...

In its simplest form, setter and getter methods of a non-concurrent resouce look
like:

class HoldDatum {
private Datum datum;
public synchronized void set (Datum d) { datum =
Solution: d; }
public synchronized Datum get () { return datum;
}
}

A resource such as an I/O stream may be accessed by a single synchronized


method. 
Java API Many of the methods of the java.util.Vector class are synchronized to ensure
Usage: single threaded access to the internal data structures of Vector objects.
See also: This pattern is used by other "temporal" patterns. 

35
+          
 


Origin: Lea 97


Reason: A method should wait to execute until a precondition holds. 
Synopsis: Use an object's methods wait and notify. 
A queue is used by two threads to exchange objects. A thread can take an object from
Example:
the queue only if the queue contains elements. 

1a: doThis( ) {concurrency=guarded} 1b: doThat(:int ) {concurrency=guarded}

UML :Thing
Class
Diagram: 1a.1: foo( ) {concurrency=guarded | !w.isOK( )} 1b.1: bar(:int ) {concurrency=guarded}

w:Widget

In its simplest form, the method guarded by a precondition looks like:

synchronized void guardedMethod () {


while (! precondition) { wait (); }
... // code requiring precondition
}

Solution: Any method that might change the precondition looks like:

synchronized void stateChangingMethod () {


... // code possibly changing precondition
notify ();
}

Both methods are synchronized on the same object. 


See also: Balking (is similar to guardedMethod, but it returns rather than waiting)

36
    
 

Origin: Lea 97


Disregard the call to a method of an object, if the state of the object is not
Reason:
appropriate to execute the call. 
Test the object's state, in a synchronized block for thread safety, and return if
Synopsis:
the state is inappropriate. 
A toilet with an automatic flusher should not begin a flush cycle when another
Example:
cycle is in progress. 

UML Class
Diagram: :Client 1:didIt:=doIt( ) :Service

In its simplest form, the potentially balking method looks like:

void balkingMethod () {
synchronized (this) {
if (! some_condition) return;
else
Solution: ... // code possibly changing
some_condition
}
... // do whatever
}

The synchronized block ensures thread safety. 


Guarded Suspension (is similar to balkingMethod, but it waits rather than
See also:
returning)

37
        

Origin: Lea 97


Reason: To implement a general purpose thread scheduling policy. 
Use two classes: a general Scheduler, which assign a resource to a thread, and a
Synopsis:
specialized ScheduleOrdering, which selects one thread among many to execute. 
Entries to log are queued while waiting to be printed. Queueing minimizes the chance of
Example:
printing entries in the wrong termporal order. 
<<interface>>
ScheduleOrdering *
2 Schedules-ScheduleOrdering-
scheduleBefore(:ScheduleOrdering):boolean
Objects-for-Processing
1

UML Scheduler

Class 1
Diagram: 2 Schedules-Request-
objects for processing

1 1
Request Processes Processor
* 1

This class implements SchedulingOrdering. Objects encapsulate a


Request
request for a Processor 
This class performs the computation abstracted by a Request. It
Processor asks the Scheduler the ok to process. It informs the scheduler
when the process is completed. 
Solution:
This class schedules Requests to the Processor. It relies on
Scheduler interface ScheduleOrdering, implemented by each Request, for
the ordering. 
Interface used to decide the order in which Requests a processed.
ScheduleOrdering
Keeps the Scheduler independend of the details of a Request. 


See also: ReadWriteLock (is a specialized form of Scheduler)


In its simplest form, the key method of Processor looks like:

void process (Request r) {


scheduler.enter (r);
... // process this request
Note: scheduler.done ();
}

The Scheduler defines a variable shared by its enter and done methods

38
Thread runningThread;

The Scheduler's enter method looks like:

void enter (Request r) {


Thread thisThread = Thread.currentThread ();
synchronized (this) {
if (runningThread == null) { // processor is free
runningThread = thisThread;
return;
}
... // place thisThread in a waiting list;
}
synchronized (thisThread) {
while (thisThread != runningThread)
thisThread.wait();
}
synchronized (this) {
remove thisThread from the waiting list;
}
}

The Scheduler's done method looks like:

void done () {
synchronized (this) {
if (there are no waiting threads) {
runningThread = null;
return;
}
runningThread = first thread in waiting list;
}
synchronized (runningThread) {
runningThread.notifyAll ();
}
}


39
&    , -    !   

Origin: Lea 97


Reason: To allow concurrent read access to an object, but exclusive write access. 
Use a specialized Scheduler whose method enter is replaced by two methods:
Synopsis:
readLock and writeLock. 
Example: An on-line auction system where remote users get and set bids. 

Data ReadWriteLock
UML Class getAttribute1 Uses 3 readLock( )
Diagram: setAttribute1 writeLock( )
... done( )

In a very simple form, a Read/Write Lock is sketched as follow.

Method readLock looks like:

void synchronized readLock () {


while (pendingWriters + activeWriters > 0)
wait ();
activeReaders++: // being reading
}

Method writeLock looks like:

void synchronized writeLock () {


pendingWriters++; // block readers
while (activeReaders + activeWriters > 0) wait
Solution: ();
pendingWriters--;
activeWriters++; // being writing
}

Method done looks like:

void synchronized done () {


if (activeWriters > 0) activeWriters--;
else if (activeReaders > 0) activeReaders--;
else error ();
notifyAll ();
}

Note that activeWriters is either 0 or 1. 


See also: Scheduler

40
     . #
    

Origin: unknown
Reason: To coordinate the asynchronous production and consumption of information. 
Producers and consumers exchange information via a queue. The code to pull
Synopsis:
information from the queue is guarded. 
A trouble-ticket dispatching system receives tickets from clients. Dispatchers pull
Example:
tickets and forward them to the appropriate troubleshooter. 
Producer
1

UML 0..* Queue-produced-objects 4 Queue

Class push(:Object)
Diagram: pull( ):Object Consume-queued-objects 4
comsumer 0..*
size( ):int
Consumer
queue 1

Thic class supplies objects representing the information used by the


Producer Consumer and places them in the Queue. Production and consumption
of objects are asynchronous. 
Solution: This class holds produced objects that cannot be consumed
Queue
immediately. 
This class pulls from the Queue and uses the object produced by the
Consumer
Producer. If the Queue is empty it waits. 


Java API The Java.io.PipedInputStream and java.io.PipedOutputStream classes together


Usage: implement a variant of the Producer-Consumer pattern called the Pipe pattern.
GuardedSuspension (it is used by this pattern)
See also: Filter (it is a simple form of this pattern)
Scheduler (this pattern is a special case of scheduling)
The coordination of producers and consumers can be managed by the queue or by the
producers and consumers themselves. The following code sketches the latter.

The producer is a thread whose run methods looks like:

public void run () {


for (;;) {
Object object = ... // produce an object
Note: synchronized (queue) {
queue.enqueue (object);
queue.notify ();
}
}
}

The consumer is a thread whose run methods looks like:

41
public void run () {
for (;;) {
synchronized (queue) {
while (queue.isEmpty ()) { queue.wait (); }
Object object = queue.dequeue ();
}
... // consume the object
}
}


) $ .      )   
  


Origin: Grand 98


Reason: To orderly shutdown a thread. 
Synopsis: Set a latch that a thread checks at strategic points of its execution. 
A server that assigns a thread to each client must handle requests to terminate a
Example:
client's thread or its own execution. 
The typical run method of a thread should look like

public void run () {


initialize ();
while (! isInterrupted ()) {
... // whatever execution
Solution: }
shutdown ();
}

Method isInterrupted tests the interrupted status of a thread. The interrupted status
is set when a thread's method interrupt is called and is cleared in various situations. 
Java API
Usage:
See also: 

42

You might also like