Compiled From Various Material By: Feng Wei
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
Adapter …………………………………………………………………………… 14
Iterator …………………………………………………………………………… 15
Bridge ……………………………………………………………………………. 16
Façade ………………………………………………………………………….… 17
Flyweight ………………………………………………………………………… 18
Dynamic Linkage ……………………………………………………………….. 19
Virtual Proxy ……………………………………………………………………. 20
Decorator ………………………………………………………………………... 21
Cache Management …………………………………………………………….. 22
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
3
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
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( )
5
Factory
Creates 1
createProduct(discriminator):Product
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
Product2WidgetA Product1WidgetA
ConcreteFactory2
UML Class 1 Creates * *
createA
Diagram: createB
...
Creates
1
ConcreteFactory1
1
Uses
createA
createB WidgetB
... *
1
Creates
* Product1WidgetB Product2WidgetB
Creates
*
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
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
8
creator
*
Create-and-register-prototype-objects
UML
Class
registrar 1
Diagram:
Client
Uses
Prototype
registerPrototype 1 1..*
...
Java API
The Prototype pattern is the very essence of JavaBeans.
Usage:
AbstractFactory, FactoryMethod, Builder, creational pattern summary
See also:
Java API The Java API class java.lang.Runtime is a singleton class. It has exactly one
Usage: instance.
See also: Immutable
9
<<constructor>>
-ReusablePool
UML Class Uses ! <<misc>>
+getInstance()
Diagram: +accquireReusable():Reusable
+releaseReusable(:Reusable)
+setMaxPoolSize(maxSize:int)
...
* 1
0..*
Reusable
10
!
"
ServiceImplFactory
createServiceImpl
UML 1
Creates #
class
diagram: Uses #
* * *
ServiceImpl1 ServiceImpl2 ...
<<interface>>
ServiceImplIF
Java API
The java.net.URL class uses the Layered Initialization pattern.
Usage:
See also: The creational patterns
11
<<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
12
#
operation( ) *
13
Java API The java.awt.event.WindowAdaptor class (intended to be subclassed rather than used
Usage: directly).
Proxy
See also:
Facade
14
&
Collection Fetches-objects-from Iterator
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
UML
Class
Diagram:
<<interface>> SpecializedImpl1
SpecializedAbstraction
Uses ' SpecializedAbstractionImpl
specializedOperation( ) 1 1
specializedOperation( ) SpecializedImpl2
16
$ Uses
1
*
Facade
UML
Class
Diagram
Java API
The java.net.URL is an example of the Façade pattern.
Usage:
Interface
See also: Proxy
Adapter
17
$
1
1 AbstractFlyweight
Client
1
$ operation(extrinsicState:object)
Uses
Uses
$ Uses
$
UML
Class Creates and Manages Reuse of 4
Diagram 1 0..* 0..* 0..*
1
Creates ' 0..*
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
!
uses '
Environment ConcreteLoadableClass
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
%
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.
20
ConcreteService AbstractWrapper
UML Class Operation( ) Operation( )
Diagram: Operation2( ) Operation2( )
... ...
ConcreteWrapperA ConcreteWrapperB
Operation( ) Operation( )
Operation2( ) Operation2( )
... ...
21
#
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.
22
#
&
Send-command (
CommandHandler
1 successor
postCommand( ) 1
UML receiver handleCommand( ):boolean
Class
Diagram:
ConcreteCommandHandler1 ConcreteCommandHandler2
23
#
1
1 creator/invoker
UML Class
Diagram: CommandManager
Creates-and-invokes *
ConcreteCommand
0..*
invokee doIt( )
undoIt( )
24
! !
parse(input:InputStream):AbstractNonterminal
, Read-tokens
1 token 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
registerColleague1(Colleague1)
1 1
registerColleague2(Colleague2)
...
handleEvent1( )
handleEvent2( )
...
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
Creates -
0..* 0..*
<<interface>> <<interface>>
MementorIF Memento member class
Target
1 object
1
+ 1
+ 1
Deserializes Read-bytes
ObjectInputStream InputStream
deserializer byte byte
consumer producer
Java API
Usage:
See also: Command (similarly, it allows state changes to be undone)
27
'
notify addObserver(:ObserverIF)
0..* removeObserver(:ObserverIF)
Observer
UML
,
Observable
Diagram: Notifies
1 1
Register-observers - - Notifies
1 1
Multicaster
addObserver(:ObserverIF)
removeObserver(:ObserverIF)
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
+operation1( )
+operation2( )
...
#enter( )
UML +start( ) : State
+processEvent(event:int) : State
Diagram:
29
(
UML Class
Diagram:
NullOperation RealOperation
30
UML
Class
Diagram:
...
ConcreteStrategy1 ConcreteStrategy2
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
)
templateMethod( )
...
#operation1
#operation2
...
UML
Diagram:
ConcreteTemplate
#operation1
#operation2
32
%
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)
... ...
33
An instance of this class is the object to be "visited". Most often is
ObjectStructure
a Composite.
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.
Sometimes methods accept and visit take one extra argument, an Object, and return a
value, an Object.
34
) *
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;
}
}
35
+
UML :Thing
Class
Diagram: 1a.1: foo( ) {concurrency=guarded | !w.isOK( )} 1b.1: bar(:int ) {concurrency=guarded}
w:Widget
Solution: Any method that might change the precondition looks like:
36
UML Class
Diagram: :Client 1:didIt:=doIt( ) :Service
void balkingMethod () {
synchronized (this) {
if (! some_condition) return;
else
Solution: ... // code possibly changing
some_condition
}
... // do whatever
}
37
UML Scheduler
Class 1
Diagram: 2 Schedules-Request-
objects for processing
1 1
Request Processes Processor
* 1
The Scheduler defines a variable shared by its enter and done methods
38
Thread runningThread;
void done () {
synchronized (this) {
if (there are no waiting threads) {
runningThread = null;
return;
}
runningThread = first thread in waiting list;
}
synchronized (runningThread) {
runningThread.notifyAll ();
}
}
39
& , - !
Data ReadWriteLock
UML Class getAttribute1 Uses 3 readLock( )
Diagram: setAttribute1 writeLock( )
... done( )
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
Class push(:Object)
Diagram: pull( ):Object Consume-queued-objects 4
comsumer 0..*
size( ):int
Consumer
queue 1
41
public void run () {
for (;;) {
synchronized (queue) {
while (queue.isEmpty ()) { queue.wait (); }
Object object = queue.dequeue ();
}
... // consume the object
}
}
) $ . )
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