Overview of Design Patterns
Patterns in Java Volume 1: A Catalog of Reusable Design Patterns
Illustrated with UML
The 41 patterns in volume 1 are organized into categories
as shown in the following table:
Fundamental Design Patterns
-
Delegation (When not to use Inheritance)
Delegation is a way of extending and reusing a class by writing another
class with additional functionality that uses instances of the original
class to provide the original functionality.
-
Interface
Keep a class that uses data and services provided by instances of other
classes independent of those classes by having it access those instances
through an interface.
Related patterns are
-
Delegation
The Delegation and Interface patterns are often used together.
-
Immutable
The Immutable pattern increases the robustness of objects that share
references to the same object and reduces the overhead of concurrent access
to an object. It accomplishes this by not allowing an object’s state information
to change after it is constructed. The Immutable pattern also avoids the
need to synchronize multiple threads of execution that share an object.
Related patterns are
-
Single Threaded Execution
The Single Threaded Execution pattern is the pattern most frequently
used to coordinate access by multiple threads to a shared object. The Immutable
object pattern can be used to avoid the need for the Single Threaded Execution
pattern or any other kind of access coordination.
-
Marker Interface
The Marker Interface pattern uses interfaces that declare no methods
or variables to indicate semantic attributes of a class. It works particularly
well with utility classes that must determine something about objects without
assuming they are an instance of any particular class.
Related patterns are
-
Snapshot
The Marker Interface pattern is used as part of the Snapshot pattern
to allow serialization of objects.
-
Proxy
The Proxy pattern forces method calls to an object to occur indirectly
through a proxy object that acts as a surrogate for the other object, delegating
method calls to that object. Classes for proxy objects are declared in
a way that usually eliminates client object’s awareness that they are dealing
with a proxy. Proxy is a very general pattern that occurs in many other
patterns, but never by itself in its pure form.
Related patterns are
-
Access Proxy
The Access Proxy pattern uses a proxy to enforce a security policy
on access to a service providing object.
-
Façade
The Façade pattern uses a single object as a front end to a
set of interrelated objects.
-
Remote Proxy
The Remote Proxy pattern uses a proxy to hide the fact that a service
object is located on a different machine than the client objects that want
to use it.
-
Virtual Proxy
This pattern uses a proxy to create the illusion that a service providing
object exists before it has actually been created. It is useful if the
object is expensive to create and its services may not be needed.
-
Decorator
The Decorator pattern is structurally similar to the Proxy pattern
in that it forces access to a service providing object to be done indirectly
through another object. The difference is a matter of intent. Instead of
trying to manage the service, the indirection object in some way enhances
the service.
Creational Patterns
-
Abstract Factory
Given a set of related abstract classes, the Abstract Factory pattern
provides a way to create instances of those abstract classes from a matched
set of concrete subclasses. The Abstract Factory pattern is useful for
allowing a program to work with a variety of complex external entities
such as different windowing systems with similar functionality.
Related patterns are
-
Factory Method
The Abstract Factory may uses the Factory Method pattern.
-
Singleton
Concrete Factory classes are usually implemented as Singleton classes.
-
Builder
The Builder pattern allows a client object to construct a complex object
by specifying only its type and content. The client is shielded from the
details of the object’s construction.
Related patterns are
-
Interface
The Builder pattern uses the Interface pattern to hide the actual class
of the object it builds.
-
Composite
The object built using the Builder pattern is typically a Composite.
-
Factory Method
The Builder pattern uses the Factory Method pattern to decide which
concrete class to instantiate to build the desired type of object.
-
Layered Initialization
The Builder pattern uses the Layered Initialization pattern to create
objects that build the desired type of object.
-
Null Object
The Null Object pattern may be used by the Builder pattern to provide
“do nothing” implementations of methods.
-
Visitor
The Visitor pattern allows the creation requesting object to be more
closely coupled to the construction of the new complex object. Instead
of describing the content of the objects to be built through a series of
method calls, the information is presented in bulk as a complex data structure.
-
Factory Method
You write a class for reuse with arbitrary data types. You organize
this class so that it can instantiate other classes without being dependent
on any of the classes it instantiates. The reusable class is able to remain
independent of the classes it instantiates by it can delegatinge the choice
of which class to instantiate to another object and referring to the newly
created object through a common interface.
Related patterns are
-
Abstract Factory
The Factory Method pattern is useful for constructing individual objects
for a specific purpose without the construction requester knowing the specific
classes being instantiated. If you need to create a matched set of such
objects, then the Abstract Factory pattern is a more appropriate pattern.
-
Template Method
The Factory Method pattern is often used with the Template Method pattern.
-
Prototype
The Prototype pattern provides an alternate way for an object to work
with other objects without knowing the details of their construction.
-
Prototype
The Prototype pattern allows an object to create customized objects
without knowing their class or any details of how to create them. It works
by giving prototypical objects to an object that initiates object creation.
The creation initiating object then creates objects by asking the prototypical
objects to make copies of themselves.
Related patterns are
-
Composite
The Prototype pattern is often used with the Composite pattern. Prototypical
objects are often composite objects.
-
Abstract Factory
The Abstract Factory pattern can be a good alternative to the Prototype
pattern if there is no need for the dynamic changes that the Prototype
pattern allows to a palette of prototypical objects.
-
Façade
The class that manages a collection of prototypical objects commonly
acts as façade that separates the other classes that participate
in the Prototype pattern from the rest of the program.
-
Factory Method
The Factory Method pattern may be an alternative to the Prototype pattern
when the palette of prototypical objects never contains more than one object.
-
Decorator
The Prototype pattern is often used with the Decorator pattern.
-
Singleton
The Singleton pattern ensures that only one instance of a class is
created. All objects that use an instance of that class use the same instance.
You can use the Singleton pattern with many other patterns. In particular,
it is often used with the Abstract Factory,
Builder
and Prototype patterns.
The Singleton pattern has some similarity to the Cache
Management pattern. A Singleton is functionally similar to a Cache
that only contains one object.
If multiple threads will be getting the instance of a singleton class,
you can use the Double
Checked Locking coding pattern to ensure that only one instance is
created while avoiding the overhead of unnecessary thread synchronization
after the instance is created.
Related patterns are
-
Shared Object
The Singleton pattern describes classes that have a single instance
that may or may not be shared. The Shared Object pattern describes objects
that are shared and may have multiple instances.
-
Object Pool
Manage the reuse of objects for a type of object that is expensive
to create or only a limited number of a kind of object can be created.
Related patterns are
-
Cache Management
The Cache Management pattern manages the reuse of specific instances
of a class. The Object Pool pattern manages and creates instances of a
class that can be used interchangeably.
-
Factory Method
The Factory Method pattern can be used to encapsulate the creation
logic for objects. However, it does not manage them after their creation.
-
Singleton
Objects that manage object pools are usually singletons.
Partitioning Patterns
-
Layered Initialization
When you need multiple implementations of an abstraction, you usually
define a class to encapsulate common logic and subclasses to encapsulate
different specialized logic. That does not work when common logic must
be used to decide which specialized subclass to create. The Layered Initialization
pattern solves this problem by encapsulating the common and specialized
logic to create an object in unrelated classes.
Related patterns are
-
Builder
The Builder pattern uses the Layered Initialization pattern to create
a specialized object for representing data in a specific form.
-
Façade
The Layered Initialization pattern uses the Façade pattern by
hiding all of the other objects participating in the pattern from clients
of service objects.
-
Factory Method
When the choice of which kind of object to create does not involve
any significant preprocessing of data, the Factory Method pattern may be
a better choice. The Layered Initialization pattern may use the Factory
Method pattern after it has decided what kind of specialized logic is needed.
-
Layered Initialization
The Layered Initialization pattern recognizes a division of responsibilities
into layers during design.
-
Composite
When more than two layers of initialization are needed for initialization
you can combine the Layered Initialization pattern with the Composite pattern
to perform initialization in as many layers as needed.
-
Filter
The Filter pattern allows objects that perform different transformations
and computations on streams of data and have compatible interfaces to be
dynamically connected to perform combinations of operations on streams
of data.
Related patterns are
-
Composite
The Composite pattern can be an alternative to the Filter pattern when
the objects involved do not have a consistent interface and they can be
composed statically.
-
Layered Architecture
The Layered Architecture pattern (described in volume 2) is similar
to the Filter pattern. The most important difference is that the objects
involved in the layered Architecture pattern correspond to different levels
of abstraction.
-
Decorator
The Filter pattern is a special case of the Decorator pattern, where
a data source or data sink object is wrapped to add logic to the handling
of a data stream.
-
Composite
The Composite pattern allows you to build complex objects by recursively
composing similar objects in a tree-like manner. The Composite pattern
also allows the objects in the tree to be manipulated in a consistent manner,
by requiring all of the objects in the tree to have a common superclass
or interface.
Related patterns are
-
Chain of Responsibility
The Chain of Responsibility pattern can be combined with the Composite
pattern by adding child to parent links so that children can get information
from an ancestor without having to know which ancestor the information
came from.
-
High Cohesion
The High Cohesion pattern (described in volume 2) discourages putting
specialized methods in general purpose classes, which is something that
the Composite pattern encourages.
-
Visitor
You can use the Visitor pattern to encapsulate operations in a single
class that would otherwise be spread across multiple classes.
Structural Patterns
-
Adapter
An Adapter class implements an interface known to its clients and provides
access to an instance of a class not know to its clients. An adapter object
provides the functionality promised by an interface without having to assume
what class is being used to implement that interface.
Related patterns are
-
Anonymous Adapter
This is a coding pattern that uses anonymous adapter objects to handle
events.
-
Façade
The Adapter class provides an object that acts as an intermediary for
method calls between client objects and one other object not known to the
client objects. The Façade pattern provides an object that acts
as an intermediary for method calls between client objects and multiple
objects not know to the client objects.
-
Iterator
The Iterator pattern is a specialized form of the Adapter pattern for
sequentially accessing the contents of collection objects.
-
Proxy
The Proxy pattern, like the Adapter pattern, uses an object that is
a surrogate for another object. However, a Proxy object has the same interface
as the object for which it is a surrogate.
-
Strategy
The Strategy pattern is structurally similar to the Adapter pattern.
The difference is in the intent. The Adapter pattern allows a Client object
to carry out its originally intended function in collaboration by calling
method of objects the implement a particular interface. The Strategy pattern
provides objects that implement a particular interface for the purpose
of altering or determining the behavior of a Client object.
-
Iterator
The Iterator pattern defines an interface that declares methods for
sequentially accessing the objects in a collection. A class that accesses
a collection only through such an interface remains independent of the
class that implements the interface.
Related patterns are
-
Adapter
The Iterator pattern is a specialized form of the Adapter pattern for
sequentially accessing the contents of collection objects.
-
Factory Method
Some collection classes may use the Factory Method pattern to determine
what kind of iterator to instantiate.
-
Null Object
Null iterators are sometimes used to implement the Null Object pattern.
-
Bridge
The Bridge pattern is useful when there is a hierarchy of abstractions
and a corresponding hierarchy of implementations. Rather than combining
the abstractions and implementations into many distinct classes, the Bridge
pattern implements the abstractions and implementations as independent
classes that can be combined dynamically.
Related patterns are
-
Layered Architecture
The Bridge design pattern is a way of organizing the entities identified
using the Layered Architecture pattern (described in volume 2) into classes.
-
Abstract Factory
The Abstract Factory pattern can be used by the Bridge pattern to decide
which implementation class to instantiate for an abstraction object.
-
Façade
The Façade pattern simplifies access to a related set of objects
by providing one object that all objects outside the set use to communicate
with the set.
Related patterns are
-
Interface
The Interface pattern can be used with the Façade pattern to
allow different sets of façade and implementation classes to be
used without client classes having to be aware of the different classes.
-
Law of Demeter
A conceptual model that uses the Law of Demeter pattern often gives
rise to a design that follows the Façade pattern.
-
Flyweight
If instances of a class that contain the same information can be used
interchangeably, the Flyweight pattern allows a program to avoid the expense
of multiple instances that contain the same information by sharing one
instance.
Related patterns are
-
Composite
The Flyweight pattern is often combined with the Composite pattern
to represent the leaf nodes of a hierarchical structure with shared objects.
-
Factory Method
The Flyweight pattern uses the factory method pattern to create new
flyweight objects.
-
Immutable
Shared flyweight objects are often immutable.
-
Dynamic Linkage
Allow a program, upon request, to load and use arbitrary classes that
implement a known interface.
Related patterns are
-
Virtual Proxy
The Virtual Proxy sometimes uses the Dynamic Linkage pattern to load
the class that it needs to create its underlying object.
-
Virtual Proxy
If an object is expensive to instantiate and may not be needed, it
may be advantageous to postpone its instantiation until the object is needed.
The Virtual Proxy pattern hides the fact that an object may not yet exist
from its clients, by having them access the object indirectly through a
proxy object that implements the same interface as the object that may
not exist. The technique of delaying the instantiation of an object until
it is actually needed is sometimes called lazy instantiation.
Related patterns are
-
Façade
The Façade pattern can be used with the Virtual Proxy pattern
to minimize the number of proxy classes that are needed.
-
Proxy
The Virtual Proxy pattern is a specialized form of the Proxy pattern.
-
Decorator
The Decorator pattern extends the functionality of an object in a way
that is transparent to its clients. It does that by using an instance of
a subclass of the original class that delegates operations to the original
object.
Related patterns are
-
Delegation
The Decorator pattern is a structured way of applying the Delegation
pattern.
-
Filter
The Filter pattern is a specialized version of the Decorator pattern
that focuses on manipulating a data stream.
-
Strategy
The Decorator pattern is useful for arranging for things to happen
before or after the methods of another object are called. If you want to
arrange for different things to happen in the middle of calls to a method,
consider using the Strategy pattern.
-
Template Method
The Template Method pattern is an alternative to the Decorator pattern
that allows variable behavior in the middle of a method call instead of
before or after it.
-
Cache Management
The Cache Management pattern allows fast access to objects that would
otherwise take a long time to access. It involves keeping a copy of objects
that are expensive to construct after the immediate need for the object
is over. The object may be expensive to construct for any number of reasons,
such as requiring a lengthy computation or being fetched from a database.
Related patterns are
-
Façade
The Cache Management pattern uses the Façade pattern.
-
Publish-Subscribe
You can use the Publish-Subscribe pattern to ensure the read consistency
of a cache.
-
Remote Proxy
The Remote Proxy provides an alternative to the Cache Management pattern
by working with objects that exist in a remote environment rather than
fetching them into the local environment.
-
Template Method
The Cache Management pattern uses the Template Method pattern to keep
its Cache class reusable across application domains.
-
Virtual Proxy
The Cache Management pattern is often used with the Virtual Proxy pattern
to make the cache transparent to objects that access object in the cache.
Behavioral Patterns
-
Chain of Responsibility
The Chain of Responsibility pattern allows an object to send a command
without knowing what object or objects will receive it. It accomplishes
that by passing the command to a chain of objects that is typically part
of a larger structure. Each object in the chain may handle the command,
pass the command on to the next object in the chain or do both.
Related patterns are
-
Composite
When the chain of objects used by the Chain of Responsibility pattern
is part of a larger structure, that larger structure is usually built using
the Composite pattern.
-
Command
The Chain of Responsibility pattern makes the particular object that
executes a command indefinite. The Command pattern makes the object that
executes a command explicit and specific.
-
Template Method
When the objects that make up a chain of responsibility are part of
a larger organization built using the Composite pattern, the Template Method
pattern is often used to organize the behavior of individual objects.
-
Command
Encapsulate commands in objects so that you can control their selection,
sequencing, queue them, undo them and otherwise manipulate them.
Related patterns are
-
Factory Method
The Factory Method pattern is sometimes used to provide a layer of
indirection between a user interface and command classes.
-
Little Language
You can use the Command Pattern to help implement the Little Language
pattern.
-
Snapshot
You can use the Snapshot pattern to provide a coarse grained undo mechanism
that saves the entire state of an object rather than a command by command
account of how to reconstruct previous states.
-
Template Method
The Template Method pattern can be used to implement the top level
undo logic of the Command pattern.
-
Little Language / Interpreter
Suppose you need to solve many similar problems and you notice that
the solutions to these problems can be expressed as different combinations
of a small number of elements or operations. The simplest way to express
solutions to these problems may be to define a little language. Common
types of problems you can solve with little languages are searches of common
data structures, creation of complex data structures and formatting of
data.
Related patterns are
-
Composite
A parse tree is organized with the Composite pattern.
-
Visitor
The Visitor pattern allows you to encapsulate logic for simple manipulations
of a parse tree in a single class.
-
Mediator
The Mediator pattern uses an object to coordinate state changes between
other objects. Putting the logic in one object to manage state changes
of other objects, instead of distributing the logic over the other objects,
results in a more cohesive implementation of the logic and decreased coupling
between the other objects.
Related patterns are
-
Adapter
Mediator classes often use adapter objects to receive notifications
of state changes.
-
Interface
The Mediator pattern uses the Interface pattern to keep the Colleague
classes independent of the Mediator class.
Low Coupling/High
Cohesion
The Mediator pattern is an good example of an exception to the advice
of the Low Coupling/High Cohesion pattern.
-
Snapshot
Capture a snapshot of an object's state so that the object's state
can be restored later. The object that initiates the capture or restoration
of the state does not need to know anything about the state information.
It only needs to know that the object whose state it is restoring or capturing
implements a particular interface.
Related patterns are
-
Command
The Command pattern allows state changes to be undone on a command
by command basis without having to make a snapshot of an object’s entire
state after every command.
-
Observer
Allow objects to dynamically register dependencies between objects,
so that an object will notify those objects that are dependent on it when
its state changes.
Related patterns are
-
Adapter
The Adapter pattern can be used to allow objects that do not implement
the required interface to participate in the Observer pattern.
-
Delegation
The Observer pattern uses the Delegation pattern.
-
Mediator
The Mediator pattern is sometimes used to coordinate state changes
initiated by multiple objects to an Observable object.
-
State
Encapsulate the states of an object as discrete objects, each belonging
to a separate subclass of an abstract state class.
Related patterns are
-
Flyweight
You can use the Flyweight pattern to share state objects.
-
Mediator
The State pattern is often used with the Mediator pattern when implementing
user interfaces.
-
Singleton
You can implement non-parametric states using the Singleton pattern.
-
Null Object
The Null Object pattern provides an alternative to using null to indicate
the absence of an object to delegate an operation to. Using null to indicate
the absence of such an object requires a test for null before each call
to the other object’s methods. Instead of using null, the Null Object pattern
uses a reference to an object that doesn’t do anything.
Related patterns are
-
Singleton
If instances of a class whose methods do nothing contain no instance
specific information, then you can save time and memory by implementing
it as a singleton class.
-
Strategy
The Null Object pattern is often used with the Strategy pattern.
-
Strategy
Encapsulate related algorithms in classes that are subclasses of a
common superclass. This allows the selection of algorithm to vary by object
and also allows it to vary over time.
Related patterns are
-
Adapter
The Adapter pattern is structurally similar to the Strategy pattern.
The difference is in the intent. The Adapter pattern allows a client object
to carry out its originally intended function by calling methods of objects
that implement a particular interface. The Strategy pattern provides objects
that implement a particular interface for the purpose of altering or determining
the behavior of a client object.
-
Flyweight
If there are many client objects, they may share strategy objects if
they are implemented as Flyweights.
-
Null Object
The Strategy pattern is often used with the Null Object pattern.
-
Template Method
The Template method pattern manages alternate behaviors through subclassing
rather than delegation.
-
Template Method
Write an abstract class that contains only part of the logic needed
to accomplish its purpose. Organize the class so that its concrete methods
call an abstract method where the missing logic would have appeared. Provide
the missing logic in subclass’ methods that override the abstract methods.
Related patterns are
-
Strategy
The Strategy pattern modifies the logic of individual objects. The
Template Method pattern modifies the logic of an entire class.
-
Visitor
One way to implement an operation that involves objects in a complex
structure is to provide logic in each of their classes to support the operation.
The Visitor pattern provides an alternative way to implement such operations
that avoids complicating the classes of the objects in the structure by
putting all of the necessary logic in a separate visitor class. The Visitor
pattern also allows the logic to be varied by using different visitor classes.
Related patterns are
-
Iterator
The Iterator pattern is an alternative to the Visitor pattern when
the object structure to be navigated has a linear structure.
-
Little Language
In the Little Language pattern, you can use the Visitor Pattern to
implement the interpreter part of the pattern.
-
Composite
The Visitor pattern is often used with object structures that are organized
according to the Composite pattern.
Concurrency Patterns
-
Single Threaded Execution
Some methods access data or other shared resources in a way that
produces incorrect results if there are concurrent calls to a method and
both calls access the data or other resource at the same time. The Single
Threaded Execution pattern solves this problem by preventing concurrent
calls to the method from resulting in concurrent executions of the method.
-
Guarded Suspension
Suspend execution of a method call until a precondition is satisfied.
Related patterns are
-
Balking
The Balking pattern provides a different strategy for handling method
calls to objects that are not in an appropriate state to execute the method
call.
-
Two-Phase Termination
Because the implementation of the Two-Phase Termination pattern usually
involves the throwing and handling of InterruptedException, its
implementation usually interacts with the Guarded Suspension pattern.
-
Balking
If an object’s method is called when the object is not in an
appropriate state to execute that method, have the method return without
doing anything.
Related patterns are
-
Double Checked Locking
The Double Checked Locking coding pattern (described in volume 2) is
structurally simillar to the Balking pattern. Its intention is different.
The balking pattern avoids executing code when an object is in the wrong
state. The Double Checked Locking pattern avoids executing code to avoid
unnecessary work.
-
Guarded Suspension
The Guarded Suspension pattern provides an alternate way to handle
method calls to objects that are not in an appropriate state to execute
the method call.
-
Single Threaded Execution
The Balking pattern is often combined with the Single Threaded Execution
pattern to coordinate changes to an object’s state.
-
Scheduler
Control the order in which threads are scheduled to execute single
threaded code using an object that explicitly sequences waiting threads.
The Scheduler pattern provides a mechanism for implementing a scheduling
policy. It is independent of any specific scheduling policy.
Related patterns are
-
Read/Write Lock
Implementations of the Read/Write Lock pattern usually use the Scheduler
pattern to ensure fairness in scheduling.
-
Read/Write Lock
Allow concurrent read access to an object but require exclusive
access for write operations.
Related patterns are
-
Single Threaded Execution
The Single Threaded Execution pattern is a good and simpler alternative
to the Read/Write Lock pattern when most of the accesses to data are write
accesses.
-
Scheduler
The Read/Write Lock pattern is a specialized form of the Scheduler
pattern.
-
Producer-Consumer
Coordinate the asynchronous production and consumption of information
or objects.
Related patterns are
-
Guarded Suspension
The Producer-Consumer pattern uses the Guarded Suspension pattern to
manage the situation of a Consumer object wanting to get an object from
an empty queue.
-
Pipe
The Pipe pattern is a special case of the Producer-Consumer pattern
that involves only one Producer object an only one Consumer object. The
Pipe pattern usually refers to the Producer object as a data source and
the Consumer object as a data sink.
-
Scheduler
The Producer-Consumer pattern can be viewed as a special form of the
Scheduler pattern that has scheduling policy with two notable features.
-
The scheduling policy is based on the availability of a resource.
-
The scheduler assigns the resource to a thread but does not need to regain
control of the resource when the thread is done so it can reassign the
resource to another thread.
-
Two-Phase Termination
Provide for the orderly shutdown of a thread or process through the
setting of a latch. The thread or process checks the value of the latch
at strategic points in its execution.
Return to Mark Grand's
home page.
Preview of Patterns in Java Volume 2
The 50 patterns in volume 2 are organized into categories as shown in the
following table:
If you have any suggestions about this page or would like to discuss a
pattern with its author, send e-mail to mgrand@mindspring.com
.
GRASP Patterns
GRASP is an acronym for General Responsibility Assignment Software Patterns.
GRASP Patterns provide guidance for assigning responsibilities to classes
and, to a limited extent, determining the classes that will be in a design.
This book discusses GRASP patterns as they are applied to object oriented
design. Most GRASP patterns apply equally well to business process reengineering.
During analysis, when you are building a conceptual model of an organization
that has more than one way to do something, GRASP patterns can provide
guidance in selecting paths through the organization to include in the
conceptual model.
-
Low Coupling/High Cohesion
If you find that a class is so highly coupled or lacking in cohesion
as to make a design brittle or difficult to modify, then apply other appropriate
GRASP patterns to reassign the class’ responsibilities.
Related patterns are
-
Interface
One form of coupling between classes is the coupling between a subclass
and its superclass. It is often possible to avoid subclassing by using
the Interface pattern.
-
Mediator
It is not necessary or even always desirable for all of the classes
in a design to have low coupling and high cohesion. Sometimes the overall
complexity of a class can be reduced by concentrating complexity in one
class. The Mediator pattern provides an example of that.
-
Composed Method
It is possible for methods to be uncohesive and difficult to work with.
Some common causes are excessive length or too many execution paths within
a method. The Composed Method pattern provides guidance of breaking up
such methods into smaller, simpler and more cohesive methods.
-
Expert
Assign a responsibility to the class that has the information needed
to carry out the responsibility.
Related patterns are
-
Low Coupling/High Cohesion
The Expert pattern promotes low coupling by putting methods in the
classes that have the information that the methods need. Classes whose
methods only need the class’ own information have less need to rely on
other classes. A set of methods that all operate on the same information
tends to be cohesive.
-
Creator
Determine which class should create instances of a class based on the
relationship between the potential creator classes and the class to be
instantiated.
-
Polymorphism
When alternate behaviors are selected based on the type of an object,
use a polymorphic method call to select the behavior, rather than using
if statements to test the type.
Related patterns are
-
Dynamic Linkage
You can implement plug-ins or pluggable software components using a
combination of polymorphism and the Dynamic Linkage pattern.
-
Pure Fabrication
Fabricate a class that does not represent a problem domain entity when
you must assign a responsibility to a class, but assigning it to a class
that represents a problem domain entity would ruin its low coupling or
high cohesion.
Related patterns are
-
Low Coupling/High Cohesion
The point of the Pure Fabrication pattern is to maintain the low coupling
and high cohesion of the classes in an object oriented design.
-
Law of Demeter
If two classes have no other reason to be directly aware of each other
or otherwise coupled, then the two classes should not directly interact.
Instead of having a class call the methods of another class that it has
no other reason to be coupled with, it should call that method indirectly
through another class. Insisting on such indirection keeps a design’s overall
level of coupling down.
Related patterns are
-
Low Coupling/High Cohesion
The fundamental motivation for the Don’t Talk to Strangers pattern
is to maintain low coupling.
-
Pure Fabrication
There are sometimes good reasons for calls made to classes added to
a design using the Pure Fabrication pattern to violate the guidelines of
the Don’t Talk to Strangers pattern.
-
Mediator
The Mediator pattern provides an example of a class created through
pure fabrication that receives direct method calls from classes unrelated
to it with a benefit that outweighs the disadvantages of the direct calls.
Controller
If a program will receive events from external sources other
than its graphical user interface, add an event class to decouple the event
source(s) from the objects that actually handle the events.
Related patterns are
-
Pure Fabrication
The Controller pattern is a specialized form of the Pure Fabrication
pattern.
-
Mediator
The Mediator pattern is used to coordinates events from a GUI.
Like controller objects, a highly coupled and incohesive mediator
object may involve less overall complexity than an arrangement that distributes
the same responsibilities over more objects.
GUI Design Patterns
-
Window Per Task
A GUI should have a separate window for each cohesive task a
user must perform. All information needed to perform the task is available
from the window. The application provides a way to navigate between windows
that allows the coordination of tasks.
Related patterns are
-
Interaction Style
Match the style of interaction offered by a GUI to the abilities
of its users and the requirements of the application. The most common styles
of interaction are Selection, Form, Direct Manipulation and Conversational
Text.
Related patterns are
-
Conversational Text
This pattern describes one of the interaction styles that this pattern
promotes.
-
Form
This pattern describes one of the interaction styles that this pattern
promotes.
-
Direct Manipulation
This pattern describes one of the interaction styles that this pattern
promotes.
-
Selection
This pattern describes one of the interaction styles that this pattern
promotes.
-
Explorable Interface
Design user interaction to be forgiving of the user’s mistakes by allowing
the user to undo actions and go back to previous decision points.
Related patterns are
-
Command
The Command pattern describes a way to undo the effects of a command
or the performance of a task.
-
Conversational Text
The Explorable Interface pattern is often used with the Conversational
Text pattern.
-
Form
The Explorable Interface pattern is often used with the Form pattern.
-
Supplementary Window
The Explorable Interface pattern is often used with the Supplementary
Window pattern.
-
Direct Manipulation
The Explorable Interface pattern is often used with the Direct Manipulation
pattern.
-
Selection
The Explorable Interface pattern is often used with the Selection pattern.
-
Snapshot
The Snapshot pattern can be used to restore the state of a program
to what it was at a previous time.
-
Conversational Text
Design a GUI to accept commands in the form of textual input.
Related patterns are
-
Explorable Interface
The Interaction Style pattern is used to decide to use the Conversational
Text pattern.
-
Interaction Style
The Interaction Style pattern is used to decide to use the Conversational
Text pattern.
-
Little Language
The Little Language pattern describes how to design and implement textual
command input as a little language.
-
Selection
Allow users to interact with a GUI by selecting commands and data values
from lists.
Related patterns are
-
Explorable Interface
The Explorable Interface pattern describes a technique for making
a selection interaction more useable.
-
Limited Selection Size
The Limited Selection Size pattern provides additional guidance in
determining the presentation of a menu interaction.
-
Form
Allow a user to enter structured data into a GUI as discrete pieces
of information.
Related patterns are
-
Ephemeral Feedback
The Ephemeral Feedback pattern provides guidance in providing brief,
short lived feedback to a user.
-
Explorable Interface
The Explorable Interface pattern describes a technique for making a
data entry form interaction more useable.
-
Selection
Data Entry Form interactions often include selection interactions to
select data values.
-
Direct Manipulation
Allow users to interact with objects by manipulating representation
of objects presented by a GUI.
Related patterns are
-
Ephemeral Feedback
The Ephemeral Feedback pattern provides guidance in providing brief,
short lived feedback to a user.
-
Explorable Interface
The Explorable Interface pattern describes a technique for making a
direct manipulation interaction more useable.
-
Selection
When a direct manipulation interaction that supports Menus are used
to select a command to manipulate previously selected objects.
-
Limited Selection Size
Design the presentation of selection interactions to avoid displaying
more than a limited number of choices at a time.
Related patterns are
-
Selection
The Limited Selection Size pattern provides guidance on designing the
presentation of selection interactions.
-
Ephemeral Feedback
Provide feedback to users about the status of their work, without interfering
with the natural flow of their work.
Related patterns are
-
Ease of Use
Use of the Ephemeral Feedback pattern can result in a GUI that presents
uses with fewer surprises, which the Ease of Use pattern says is a good
thing.
-
Disabled Irrelevant Things
Hide or disable GUI elements that that are not relevant in the
current context.
Related patterns are
-
Selection
The Disabled Irrelevant Things pattern is used with the Selection pattern.
-
Supplementary Window
Display a window for a user interaction that supplements a parent window’s
interaction. The purpose of the supplementary window is to collect information
for the parent window’s interaction, display additional information about
the parent window’s interaction or provide a notification about the status
of the parent’s interaction. The supplementary window is shorter lived
than its parent.
Related patterns are
-
Limited Selection Size
Use the Limited Selection Size pattern to decide if a dialog will have
pull-down menus.
-
Window Per Task
The Supplementary Window Pattern is partially motivated by the Window
Per Task pattern.
-
Step-by-Step Instructions
Lead a user through the steps of a task, so that the GUI tells the
user what to do next, rather than the user telling the GUI what to do next.
Related patterns are
-
Selection
Implementations of the Step-by-Step Instructions pattern usually rely
heavily on selection interactions to acquire information from users.
-
Supplementary Window
Sometimes the Step-by-Step Instructions pattern is used to supplement a
GUI that requires the user to lead the program through tasks. Wizards that
are available in popular word processing and spreadsheet programs are an
example. When the Step-by-Step instructions pattern is used to design a
supplementary GUI, it is usually in the context of a dialog.
Organizational Coding Patterns
The patterns in this chapter provide guidance in organizing your code
in ways that promote readability and maintainability. A principle that
underlies many of these patterns is that simple code is easier to understand
and less likely to contain bugs.
-
Accessor Method Name
Use names and signatures for accessor methods that are easy to read
and conform to the JavaBeans specification.
-
Anonymous Adapter
Use anonymous adapter objects to handle events. This simplifies the
code and allows code relating to the same event source to be in the same
part of the source code.
Related patterns are
-
Adapter
The Anonymous Adapters pattern uses Adapter objects.
-
Mediator
If handling events from multiple sources involves managing or
using common or interrelated state information, then the Mediator pattern
may provide a better way to handle the events.
-
Hashed Adapter Objects
You can use the hashed Adapter Objects pattern to provide a more flexible
way to manage event handlers than the Anonymous Adapters pattern.
-
Symbolic Constant Name
Use symbolic names for constants. A meaningful name makes the
purpose of the constant clear to someone reading the code. Symbolic names
can also simplify maintenance.
Related patterns are
-
Immutable
The Immutable pattern describes other uses for immutable objects.
-
Switch
Code that uses the Switch pattern should also use the Symbolic Constant
Name pattern.
-
Define Constants in Interfaces
Avoid having to qualify symbolic constant names with the name of the
class that defines them. Define them in an interface. That way, any class
that implements the interface can use the symbolic names without any qualification.
Related patterns are
-
Switch
Select a piece of code to execute from multiple alternatives based
on an int data value by using a switch statement.
Related patterns are
-
Hashed Adapter Objects
Switch statements associate int values pieces of code. The
Hashed Adapter Objects pattern associates objects with pieces of code.
-
Symbolic Constant Name
Code that uses the Switch pattern should also use the Symbolic Constant
Name pattern.
-
Polymorphism
In many situations, polymorphic method calls are a more appropriate
technique than switch statements. However, people with a background in
procedural programming who are new to object oriented techniques often
use switch statements when polymorphic method calls would be more appropriate.
-
Extend Super
Implement a method that modifies the behavior of a superclass’ method
by calling the superclass’ method.
Related patterns are
-
Composed Method
The Composed Method pattern describes the more general case of composing
the behavior of a method from the behavior of other methods.
-
Template Method
The Template Method pattern describes a way to design a class that
plans for its behavior to be extended by a subclass’s methods. It provides
more flixibility and control over how a subclass extends the behavior of
its superclass than the Extend Super pattern at the expense of greater
complexity. In particular, the Template Method patterns allows behavior
of a subclass to occur in the middle of the exection of superclass’s methods.
The template method pattern can also be used to force a subclass to extend
a superclass in predefined ways.
-
Intention Revealing Method
If the intention of a call to a general purpose method is not obvious,
then define a method with a meaningful name to call the general purpose
method.
Related patterns are
-
Intention Revealing Method
The sort of methods described by the Intention Revealing Method pattern
should be the smallest methods that you create when applying the Composed
Method pattern.
-
Composed Method
The Composed Method pattern provides other reasons for moving
code into a separate method.
-
Façade
After applying the Composed Method pattern, you may decide to break
a class up into smaller classes with the original class acting as a façade.
-
Conditional Compilation
Control whether a compiler includes statements for debugging in the
byte codes it generates or ignores those statements.
Related patterns are
-
Assertion Testing
The Conditional Compilation pattern is often used with the Assertion
Testing pattern.
-
White Box Testing
The Conditional Compilation pattern is often used with the White Box
Testing pattern.
-
Composed Method
Reorganize methods that are too large to easily understand into smaller
methods.
Related patterns are
-
Intention Revealing Method
The sort of methods described by the Intention Revealing Method pattern
should be the smallest methods that you create when applying the Composed
Method pattern.
-
Maximize Privacy
The Maximize Privacy pattern provide the motivation for making sub-methods
private that are created by applying the Composed Method pattern.
Façade
-
After applying the Composed Method pattern, you may decide to break a class
up into smaller classes with the original class acting as a façade.
-
Checked Versus
Unchecked Exceptions
As part of its contract with its callers, a method may be expected
to throw exceptions under certain circumstances. Those exceptions should
be checked exceptions. Any exceptions a method throws that are outside
of its contract, such exceptions to indicate internal errors or to help
with debugging, should be unchecked exceptions.
Related patterns are
-
Assertion Testing
The Assertion Testing pattern provides additional guidance about checked
or unchecked exception to report unsatisfied assertions.
-
Conditional Compilation
The Conditional Compilation pattern can be used to prevent debug code
that throws unchecked exceptions from being included in a production version
of a class.
-
Convert Exceptions
Many programs are organized into layers related to different domains,
such as database management and an application domain. In such programs,
some classes are part of one domain but have methods that call methods
of classes that belong to another domain. Such methods should convert exceptions
they do not catch from the other domain to their own domain.
Related patterns are
-
Server Socket
You need to write code to manage the server side of a socket based
network connection. The code that you write follows a very consistent pattern
that revolves around ServerSocket and Socket objects.
Related patterns are
-
Client Socket
The Client Socket pattern described the common logic for implementing
clients.
-
Thread Pool
The Thread Pool pattern describes a more efficient way to to manage
server threads. The Thread Pool pattern will be described in Volume 3.
-
Two Phase Termination
The Two Phase Termination pattern explains how to use a Thread object’s
interrupt method to request that the thread show down in an orderly manner.
-
Client Socket
Most uses of the Socket class to implement a client follow a very consistent
coding pattern.
Related patterns are
-
Heartbeat
The Heartbeat pattern (described in Volume 3) describes a technique
that allows a client program to detect that a server has gone down.
-
Server Socket
The ServerSocket pattern described the common logic for implementing
servers.
Code Optimization Patterns
The patterns in this chapter can be used to improve the performance
of a program in ways that a compiler’s automatic optimizations cannot accomplish.
Like any other kind of optimization, you should use the patterns in this
chapter only after you have established a definite need for them. For example,
the Loop Unrolling pattern reduces the amount of time required to execute
a loop. It does so at the expense of making the code larger and harder
to understand and maintain. If the program makes enough loop iterations
for a small reduction in the duration of each iteration to produce a noticeable
improvement, that is a good application of the Loop Unrolling pattern.
If applying the Loop Unrolling pattern does not produce a noticeable improvement,
then you have made you program more difficult to understand an maintain
with no corresponding benefit.
The usual way to determine what to optimize is to run a program using
a good execution profiling tool. Such tools are able to tell you how much
time a program spends in different methods or statements. They are also
able to indicate the percentage of time that the program spent in each
place and the number of times that each statement or method was executed.
-
Hashed Adapter Objects
Dispatch a method call to an adapter object associated with an arbitrary
object. The arbitrary object is used to find the adapter object in a hash
table. The Hashed Adapter Objects pattern is most commonly used when an
object must be created from unencapsulated data or unencapsulated data
must be dispatched to an object.
Related patterns are
-
Adapter
The Hashed Adapter Objects pattern uses Adapter objects.
-
Lookup Table
Both the Hashed Adapter Objects pattern and the Lookup Table pattern
involve the use of an aggregation. However, the aggegation serves a different
purpose for each. The Lookup Table pattern uses an aggregation of precomputed
results to save the time it would take to compute those results in the
future. For the Hashed Adapter Objects pattern, it is that data structure
that implements the aggregation that is the source of the time savings.
-
Polymorphism
When it is possible to select a behavior based on the type of an object,
the Polymorphism pattern produces a simpler result than the Hashed Adapter
Objects pattern.
-
Single Threaded
Execution
The Single Threaded Execution pattern is used to coordinate access
by multiple threads to the hash table used by the Hashed Adapter Objects
pattern.
-
Strategy
The Hashed Adapter Objects pattern can used to design the selection
of strategy objects in the Strategy pattern.
-
Lazy Initialization
Delay the creation of an object or other expensive action needed to
initialize a variable until it is known that the variable will be used.
Related patterns are
-
Maximize Privacy
The Maximize Privacy pattern provides a justification for making a
lazily initialized variable private.
-
Virtual Proxy
Like the Lazy Initialization pattern, the Virtual Proxy pattern can
be used to delay a computation or the creation of an object until it is
actually needed. The difference is that the Virtual Proxy pattern uses
a proxy object to hide the computation; the Lazy Initialization pattern
uses a method to hide the computation.
-
Double Checked Locking
A multi-threaded program does not initialize a resource until
it actually needs the resource. One thread recognizes that that resource
is not yet initialized when another thread has already begun the initialization.
Avoid duplicating the initialization effort by coordinating the actions
of multiple threads.
Related patterns are
-
Balking
The Balking design pattern is usually implemented using the same if-synchronized-if
structure as the Double Checked Locking pattern.
-
Lazy Initialization
The Double Checked Locking pattern can be used to ensure the integrity
of the Lazy Initialization pattern when it is used in multi-threaded application.
-
Singleton
The Double Checked Locking pattern can be used in a thread safe and
efficient implementation of the Singleton pattern.
-
Virtual Proxy
The Double Checked Locking pattern can be used in a thread safe
implementation of the Virtual Proxy pattern.
-
Loop Unrolling
Reduce the overhead of a loop’s control logic by increasing the amount
of work it does in each iteration so that it can accomplish the same amount
of work in fewer iterations. This pattern trades memory for speed.
-
Lookup Table
Save the memory consumed by complex code and the time it takes to execute
by precomputing the results and putting them in a lookup table.
Related patterns are
-
Hashed Adapter Objects
Both the Hashed Adapter Objects pattern and the Lookup Table pattern
involve the use of an aggregation. However, the aggegation serves a different
purpose for each. The Lookup Table pattern uses an aggregation of precomputed
results to save the time it would take to compute those results in the
future. For the Hashed Adapter Objects pattern, it is that data structure
that implements the aggregation that is the source of the time savings.
Robustness Coding
Patterns
-
Assertion Testing
Verify that a method conforms to its contract with its callers by inserting
code to test its preconditions, postconditions, invariants and data conditions
and run time.
Related patterns are
-
Checked vs. Unchecked Exceptions
The Checked vs. Unchecked Exception pattern explains reasons for using
unchecked exceptions to indicate assertion failures.
-
Conditional Compilation
You can use the Conditional Compilation pattern with the Assertion
Testing pattern to control whether or not assertion testing code is included
in a particular configuration of a program.
-
Guaranteed Cleanup
Ensure that internal data are in a consistent state if an operation
is unable to execute to its normal completion. Ensure that external resources
are consistent state and, if appropriate, released after an operation is
unable to execute to its normal completion.
-
Maximize Privacy
Make members of classes as private as possible.
Related patterns are
-
Return New Objects
from Accessor Method
Accessor methods return values or objects that indicate an object’s
state. If the objects that an accessor method returns are mutable, then
they should be copies rather than the actual state determining objects.
That prevents changes to the returned object from also changing the state
of the accessor method’s associated object.
Related patterns are
-
Copy Mutable Parameters
The Return New Objects from Accessor Method pattern avoids the situation
of an object sharing its state determining objects with callers of its
accessor methods. The Copy Mutable Parameters pattern avoids a similar
situation with callers that pass state determining objects into its constructors
and methods.
-
Copy Mutable Parameters
Objects may be passed to a method or constructor that will be used
to determine the state of its associated object. If the passed objects
are mutable, then copies of them should be used to determine the object’s
state, rather than the original passed object. That prevents changes to
the passed object from also changing the state of the object associated
with the method or constructor.
Related patterns are
-
Return New Objects from
Accessor Method
The Copy Mutable Parameters pattern avoids the situation of an object
sharing its state determining objects with callers of its methods that
specify those objects. The Return New Objects from Accessor Method pattern
avoids a similar situation with callers of methods that return state determining
objects.
Testing Patterns
-
White Box Testing
White box testing is used more often at the unit testing level than
at larger levels of granularity. This is because at the unit testing level
there are fewer combinations of execution paths to consider. It is also
because white box testing at the unit level makes classes easier to reuse
and lowers long term software maintenance costs.
-
Integration Testing
Test individually developed classes together for the first time.
Related patterns are
-
System Testing
Integration testing generally involves testing smaller groups of classes
than you test during system testing. Integration testing can be considered
an activity that smooths the transition from not being sufficiently along
in the development cycle to do system testing to a situation where system
testing is a productive activity.
-
Unit Testing
Unit testing deals with individual classes or very small groups of
classes. System Testing deals with larger groups of classes.
-
System Testing
Test a program as a whole entity, in an environment similar to the
one it is intended to be run in, to ensure that it conforms to its specifications.
Related patterns are
-
Integration Testing
Integration testing ensures that the software being tested is in a
sufficiently functional state that it is possible to run groups of system
tests and get meaningful results.
-
Regression Testing
Regression testing allows you to use system tests to monitor the progress
of programmers and to measure the overall readiness of the software to
meet its requirements and specifications.
-
Regression Testing
Keep track of the outcomes of testing software with a suite of tests
over time. This allows you to monitor the progress of programmers in completing
their coding as they make incremental changes. It allows you to determine
if a change to a program introduced new bugs.
Related patterns are
-
Systems Testing
Regression testing is commonly used with system testing.
-
Unit Testing
Regression testing is sometimes used with unit testing.
-
Acceptance Testing
Acceptance testing is testing done to ensure that delivered software
meets the needs of the customer or organization that the software was developed
for. Such testing is usually performed by the organization that the software
was developed for. Acceptance testing is done according to a plan. The
purpose of an acceptance testing plan is to ensure that software developers
and the organization that they develop a software system for agree on when
the software is ready to be delivered by developers.
Related patterns are
-
Systems Testing
System testing is often the final form of testing that a software developer
performs on software before turning it over to the developer’s customer
for acceptance testing.
-
Clean Room Testing
People designing software should not discuss specifications or their
implementation with people designing tests for the software.
Return to Mark Grand's
home page.
Preview of Patterns in Java Volume 3
The intended focus is design patterns for the enterprise (work in progress).
Transaction Patterns
-
Two Phase Commit
The Two Phase Commit pattern can be used to ensure the ACID properties
of a composite transaction composed from simpler ACID transactions.
-
Mailbox
When there is a need to ensure the reliability a composite transaction,
you will want to take steps to ensure the reliability of the component
transactions that constitute it. If the composite transaction is distributed,
you will also want to ensure the reliable transmission of messages between
the objects that participate in the transaction by such means as the Mailbox
pattern.
-
Two Phase Commit
If a transaction is composed of simpler transactions distributed across
multiple database managers, you want them to either all complete successfully
or to all abort, leaving all objects as they were before the transactions.
You achieve this by making an object responsible for coordinating the transactions
so that they all complete successfully or all abort.
Related patterns are
-
ACID Transaction
The Two Phase Commit pattern is used to build composite transactions
having the ACID properties from component transactions that have the ACID
properties.
-
Composite Transaction
The Two Phase Commit pattern is used with the Composite Transaction
pattern
-
Decorator
The Decorator pattern provides the basis for the organization of the
wrapper objects used in the Two Phase Commit pattern.
-
Heartbeat
The Heartbeat pattern may be used with the Two Phase Commit pattern
to ensure that the Coordinator object is able to detect catastrophic failures
of component transactions in a bounded amount of time.
Audit Trail
You need to verify that transactions are being processed correctly
and honestly. Maintain an historical record of transactions that have been
applied to an object or set of objects. The record should contain enough
detail to determine how the objects affected by the transactions reached
their current state.
Related patterns are
-
ACID Transaction
If the transactions in an historical record do not have the ACID properties,
then it may not be possible to unambiguously determine the effect of each
transaction on an object.
-
Snapshot
The Snapshot pattern provides advice on how to capture the state of
an object.
Distributed Architecture
Patterns
Shared Object
You have some information or a limited quantity of a resource. You
share objects among multiple clients to share encapsulated information
or underlying resources. You centrally manage the object sharing with a
separate object, so the sharing does not add to the complexity of the objects
being shared or the objects sharing them.
Related patterns are
-
Static Locking Order
If Client objects work with multiple Manager objects to concurrently
access multiple types of Resource objects, it is possible for
two client objects to deadlock while waiting for different resources. Client
objects should use the Static Locking Order pattern to avoid this sort
of deadlock.
-
Object Replication
The Object Replication pattern provides a decentralized way for the
clients of an object to share information.
-
Object Request Broker
The Object Request Broker pattern can be used to allow objects to be
shared by remote clients.
-
Scheduler
The Scheduler pattern describes a way to schedule access, one client
at a time, to shared resources.
-
Read/Write Lock
The Read/Write lock pattern is a specialized form of the Scheduler
pattern. It allows multiple clients to concurrently have read access to
a resource, but only allows exclusive access for a client that modifies
the resource.
-
Singleton
The Singleton pattern describes classes that have a single instance
that may or may not be shared. The Shared Object pattern describes objects
that are shared and may have multiple instances.
-
Flyweight
If an object has no intrinsic state, then there is generally no need
to impose concurrency restrictions on access to the object. The Shared
Object pattern is inappropriate for sharing such objects, because it adds
unnecessary overhead. The Flyweight pattern (found in Volume 1) describes
a way that objects with no intrinsic state can be shared by local clients
any concurrency restrictions.
Object Request Broker
Objects in a distributed environment need to call methods of
remote objects. For remote calls to work, many details must be just right.
Provide an infrastructure that allows objects to make remote calls, with
most of the details of the call hidden and handled automatically by the
infrastructure.
Related patterns are
-
Object Identifier
The Object Identifier pattern provides additional guidance on uniquely
identifying possibly remote objects.
-
Heartbeat Pattern
The Heartbeat pattern provides a general purpose way to detect when
the caller of a remote method will never see the call complete because
the machine that the remote call runs on has crashed or the network connection
to the remote machine has been lost.
-
Registry
The Registry pattern describes a way for an Object Request Broker implementation
to find remote objects that have a know name or unique object identifier.
-
Thread Pool
CallDispatcher objects need a thread to process each remote call. An
implementation of the Object Request Broker pattern can use the Thread
Pool pattern to recycle threads and avoid the expense of creating new threads.
-
Object Replication
You need to improve the throughput or availability of a distributed
computation. A distributed computation is a computation that involves objects
that reside on multiple computing elements and are able to communicate
with each other. In some circumstances, it is possible to improve the availability
and throughput of a computation by replicating an object onto multiple
computing elements while maintaining the illusion to the object’s clients
of there only being a single object.
Related patterns are
-
High Availability
The High Availability pattern is a more specialized pattern that describes
the use of replication to make objects highly available.
-
Optimistic Concurrency
The Optimistic Concurrency pattern describes how to update data without
the use of locks.
-
Immutable
The Immutable pattern explains the simplicity and safety that comes
from designing objects to be immutable.
-
Object Request Broker
The Object Request Broker pattern allows an object to be used in multiple
places at the same time without it being in multiple places or replicated.
-
Redundant Independant Objects
You need to ensure the availability of an object even if it or the
platform it is running on experience a failure. You accomplish this by
providing redundant objects that do not rely on any single common resource.
Related patterns are
-
Prompt Repair
The Prompt Repair pattern is often used with the Redundant Independent
Objects pattern to ensure the continued availability of a set of redundant
independent objects even after a failure occurs.
-
Object Replication
The Redundant Independent Objects pattern is a specialized version
of the Object Replication pattern.
-
Prompt Repair
When one of a set of redundant independent objects fails, one fewer
failures must occur before the entire set of redundant objects becomes
unavailable. To minimize the likelihood of a catastrophic failure, repair
the failed object as soon as possible.
Related patterns are
-
Redundant Independent Objects
The Prompt Repair pattern is use with the Redundant Independent Object
pattern.
-
Process Pair
The Process Pair pattern is used to ensure that software components
on the same computing element are restarted when they fail.
-
Snapshot
The Snapshot pattern (described in Volume 1) can be used to implement
checkpoint/restart.
-
Mobile Agent
An object needs to access very large volume of remote data. To conserve
network bandwidth, Instead instead of bringing data to an object, move
the object to the data.
Related patterns are:
-
Object Request Broker
The Object Request Broker pattern is usually used with the Mobile Agent
pattern to facilitate communications between mobile agents and other objects.
Mobile agents can be implemented on top of the Object Request Broker pattern.
-
Object Replication
One of the applications of the Object Replication pattern is to ensure
that an object is near its accessors. The Mobile Agent pattern provides
a way for an object’s accessors to be near the object.
-
Demilitarized Zone
You don’t want hackers to be able to gain access to servers containing
sensitive information if they are able to compromise the security of a
publicly accessible server. Put servers that are accessible to the public
Internet on a publicly accessible LAN that connects with bothbetween your
private networkfirewall and the public Internet.
Related pattern are
-
Protection Proxy
The Protection Proxy pattern, at the object level, is structurally
similar to the Demilitarized Zone pattern at the network level.
-
Process Pair
To keep a process or software component highly available, you want
it to be automatically restarted if it fails. Organize highly available
software components in pairs, so that if one fails the other restarts it.
Related pattern are
-
Heartbeat
The Process Pair pattern uses the Heartbeat pattern.
Distributed Computing Patterns
-
Object Identifier
You need to uniquely identify an object that exists in multiple environments.
Assign a globally unique identifier to the object, allowing it to have
a unique identity when it is shared between programs or databases.
Related patterns are
-
Objecct Request Broker and Registry
You can use the Object Request Broker pattern with the Registry pattern
to encapsulate an implmentation of the Object Identifier pattern and minimize
the number of classes that are dependent on it.
-
Mobile Agent
The Mobile Agent pattern uses the Object ID pattern.
-
Object Replication
The Object Replication pattern uses the Object ID pattern.
-
Registry
Objects need to contact another object, knowing only the object’s name
or the name of the service it provides, but not its how to contact it.
Provide a service that takes the name of an object, service or role and
returns a remote proxy that encapsulates the knowledge of how to contact
the named object.
Related patterns are
-
Protection Proxy
Malicious objects may attempt to violate the integrity of other objects
by using reflection or other means to access methods or variables they
should not. You can prevent this by requiring other objects to access sensitive
objects through a proxy that limits access based on security considerations.
The proxy implements measures to ensure that other objects do not gain
access to features of a sensitive object that they are not entitled to.
Related patterns are
-
Proxy
The Protection Proxy pattern is a specialized version of the Proxy
pattern.
-
Template Method
The Protection Proxy pattern uses the Template Method pattern to abstract
out the reusable portion of the thread management logic.
-
Thread Pool
You can use the Thread Pool pattern with the Protection Proxy pattern
to create a multi-threaded proxy.
-
Publish-Subscribe
You need to provide timely delivery of messages to one or more objects.
Deliver messages to subscribed recipient objects by transmitting each message
to each recipient. Ensure reliable delivery by repeating the transmission
after an attempt fails until delivery is successful.
Related patterns are:
-
Object Request Broker
The Publish-Subscribe pattern is often used with the Object Reqest
Broker pattern to deliver messages to remote objects.
-
Mailbox
The Mailbox pattern provides an alternate solution for the reliable
delivery of messages.
-
Registry
The registry pattern provides a way for Subscriber objects to find
Publisher objects.
-
Retransmission
You need to ensure that an object can reliably send a message to a
remote object. Following the maxim, “If at first you don’t succeed, try
again”, you design the object to handle a failure to send a message by
trying again until the send is successful.
Related patterns are:
-
Object Request Broker
The Retransmission pattern is often used with the Object Request Broker
pattern to deliver messages to remote objects.
-
Mailbox
The Mailbox pattern provides an alternate solution for the reliable
delivery of messages.
-
High Availability
You can use the High Availability pattern to minimize the likelihood
that a DeliveryAgent object will crash or become otherwise unavailable.
-
Process Pair
The Process Pair pattern describes a way to ensure that a DeliveryAgent
object is automatically restarted after a crash.
-
Mailbox
You need to provide reliable delivery of messages to objects. Facilitate
the delivery of messages by storing messages for later retrieval by each
recipient.
Related patterns are:
-
Publish-Subscribe
The Publish-Subscribe pattern provides an alternate solution for the
reliable delivery of messages.
-
High Availability
The High Availability pattern can be used to ensure that a MailboxServer
is highly available.
-
Object Request Broker
The Mailbox pattern is often used with the Object Request Broker pattern
to deliver messages to remote objects.
-
Process Pair
The Process Pair pattern describes a way to ensure that a MailboxServer
object is automatically restarted after a crash.
-
Registry
The registry pattern provides a way for Subscriber objects to find
MailboxServer objects.
-
Heavyweight/Lightweight
Object
You are designing an application client that should be as small and
thin as possible. The client must access some objects that have many attributes
and/or attributes that are large objects. The client does not always need
the attributes, so you arrange for the client to download the objects without
the attributes and then lazily download the attributes on an as needed
basis.
Related Patterns are:
-
Object Request Broker
The Heavyweight/Lightweight pattern is usually implemented using the
Object Request Broker to facilitate communication between the client and
the server.
-
Lazy Initialization
The lazy Initialization pattern can be used to manage the download
of Data objects if client objects are responsible for the download of their
own Data object.
-
Virtual Proxy
The Virtual Proxy pattern should be used to manage the download of
Data objects if the same class is used to implement the client and server
version of the shared object.
-
Object Replication
The Object Replication pattern addresses issues related to keeping
the state of the client and server objects consistent.
-
Facade
Like a façade object, a lightweight object hides the details
of accessing objects behind it.
-
Heartbeat
While a remote object is performing an operation on behalf of a client,
periodically send a message back to the client indicating that the remote
object is still alive.
Related patterns are:
-
Object Request Broker
The Heartbeat pattern is used with the Object Request Broker pattern.
-
Connection Multiplexing
Whether or not the ORB being used with the Heartbeat pattern implements
the Connection Multiplexing pattern can determine how you choose to implement
the Heartbeat pattern.
-
Connection Multiplexing
You are designing a distributed system in which one object may establish
many connections with another object. To avoid the overhead of setting
up and shutting down many connections between the same two objects, you
arrange for one actual connection to carry the contents of multiple virtual
connections.
Related patterns are
-
Object Pool
The Connection Multiplexing pattern uses the Object Pool pattern to
manage data buffers.
-
Object Identifier
The ConnectionID objects used by the Connection Multiplexing pattern
are an application of the Object Identifier pattern.
-
Scheduler
The Scheduler pattern can be used to ensure that all virtual connections
get their fair share of the actual connection’s bandwidth. The Scheduling
pattern describes how to enforce a policy that determines when a thread
is scheduled to use a resource.
Concurrency Patterns
-
Session Object
A server’s sessions with clients have state information associated
with them, but you don’t want to duplicate a lot of objects for each session.
Use a single object to contain all the state information needed during
a session by the server and make that object accessible to all other objects
that need state information for the current session.
Related patterns are
-
Singleton
The Singleton pattern (described in Volume 1) uses a single instance
of a class for an entire program. The Session pattern uses a single instance
of a class per session.
-
Thread Pool
You can use the Thread Pool pattern to manage the association between
threads and sessions over time.
-
Lock File
A program will need to have exclusive access to an external resource.
You design the program to check for the existence of a lock file prior
to accessing the resource. If the lock file exists, the program does not
use the resource. If the lock file does not exist, the program creates
the file and then uses the resource.
Related patterns are
-
Static Locking Order
The Static Locking Order pattern is used with the Lock File pattern
when there are multiple resources to be coordinated, in order to avoid
deadlocks.
-
ACID Transaction
The lock file pattern may be used in the implementation of the ACID
Transaction pattern.
-
Static Locking Order
If two objects need exclusive access to the same set of resources,
they can become deadlocked with each holding a lock on one resource and
waiting for the other to release its resource. You can avoid such deadlocks
by ensuring that all objects acquire locks on resources in the same order.
Related patterns are
-
ACID Transaction
The Static Locking Order pattern can be used in the design of ACID
transactions.
-
Lock File
The Static Locking Order pattern can be used with the Lock File pattern
to avoid deadlocks.
-
Optimistic Concurrency
Improve throughput of transaction processing by not waiting for locks
that a transaction will need. Instead, be optimistic and perform the transaction
logic on private copies of the records or objects involved. Do insist that
the locks be granted before the updates can be committed, but abort the
transaction if conflicting updates were made prior to the granting of the
locks.
Related patterns are
-
ACID Transaction
The Optimistic Concurrency pattern can be used in the implementation
of the ACID Transaction pattern.
-
Object Replication
The Optimistic Concurrency pattern can be used in the implementation
of the Object Replication pattern.
-
Thread Pool
The nature of many servers is that they are presented with a steady
stream of tasks to perform that must each be performed in their own thread.
Creating a thread is a relatively expensive operation. Avoid the expense
of creating a thread for each task by reusing threads.
Related patterns are
-
Object Pool
The Thread Pool pattern is a specialized form of the Object Pool pattern
described Volume 1.
-
Factory Method
Implementations of the Thread Pool pattern may use the Factory Method
pattern to allow greater flexibility in how they create new threads.
-
Singleton
The Singleton pattern is often used with the Thread Pool pattern to
ensure that all classes that want to use a ThreadPool object use the same
ThreadPool object.
-
Guarded Suspension
Implementations of the Thread Pool pattern directly or indirectly use
the Guarded Suspension pattern to manage the queuing of tasks.
-
Cache Consistency
A cache can be used to keep a local copy of data from a remote data
source. From time to time, the content of the data in the remote data source
may change. You want a local cache to reflect such changes in a remote
data source. Ensure that the data in the local cache matches the remote
data source within a bounded amount of time by considering data in a cache
to have a maximum useful lifetime.
Related patterns are
-
Cache Management
The Cache Consistency pattern is a refinement to the Cache Management
pattern. That discussion includes a much more detailed discussion of caching.
-
Scheduler
The Cache Consistency pattern uses the Scheduler pattern.
-
Heavyweight/LightWeight
Application clients may use the Cache Consistency pattern with the
Heavyweight/Lightweight pattern to manage lightweight objects.
-
Deep Transaction Nesting
Implement the ability to restore the original state of objects altered
by possibly nested atomic transactions by saving the state of an object
on a stack. This technique is most commonly used for transactions that
only alter local objects or objects that are otherwise cheap to access.
Related patterns are
Temporal Patterns
-
Time Server
In order for some distributed applications to function correctly, the
clocks on the computers they run on must be synchronized. Ensure that clocks
on multiple computers are synchronized by synchronizing them with a common
clock.
Related patterns are
-
Versioned Object
Distributed applications that use the Versioned Object pattern are
likely to also use the Time Server pattern.
-
Temporal Property
Distributed applications that use the Temporal Property pattern are
likely to also use the Time Server pattern.
Versioned Object
You may need to access pervious or future states of an object. When
an object gets a new state, keep both the object’s new state and its previous
states. Identify the states by a timestamp or a version number. Allow access
to a specific state of an object by identifying its timestamp or version
number.
Related patterns are
-
Time Server
The Versioned Object pattern is often used in conjunction with the
Time Server pattern to ensure consistent timestamping of object versions.
-
Virtual Proxy
The Virtual Proxy pattern is sometimes used with the Versioned Object
pattern to avoid having to load all the states of an object from a persistant
store.
-
Temporal Property
The Temporal Property pattern provides a alternate way of organizing
changes in an object’s state over time. It is more appropriate for classes
whose state changes tend to involve only one attribute at a time.
Temporal Property
The values of an object’s attributes may change over time. They usually
change independently of each other. Keep historical values of attributes
in a way that allows clients to get the effective value of a particular
attribute as of a particular time.
Related patterns are
-
Time Server
The Temporal Property pattern is often used in conjunction with the
Time Server pattern to ensure consistent timestamping of property values.
-
Versioned Object
The Versioned Object pattern provides a alternate way of organizing
changes in an object’s state over time. It is more appropriate for classes
whose state changes tend to involve changes to multiple attributes.
Database Patterns
-
Persistence Layer
Keep dependencies on the details of persisting objects or on a specific
database out of application specific classes by organizing persistence
related details into classes that make up a persistence layer.
Related patterns are
-
Virtual Proxy
The Virtual Proxy pattern, described in Volume 1, may be used by an
implementation of the Persistence Layer pattern to defer the fetching of
objects that are part of a more complext object but may not be needed for
some uses of the complex object.
-
CRUD
The CRUD pattern is used to design interfaces for the Persistence pattern
for objects responsible for persisting business objects.
-
Stale Object
The Stale Object pattern is used with the Persistence Layer pattern
to ensure the consistency of updates.
-
Change Manager
The Change Manager pattern is often used with the persistence pattern
in order to determine, based on the state of an object whether it needs
to be written to the persistent store or not.
-
Object ID Manager
The Object ID Manager pattern is used with the Persistence Layer pattern
to generate object IDs that will be unique across all domains that an object
will be used in or from.
-
Transaction Manager
The Persistence layer pattern uses the Transaction Manager pattern
to manage transactions.
-
Connection Manager
The Connection Manager pattern is used in implementing the Persistence
Layer pattern.
-
Abstract Factory
The Persistence Layer pattern uses the Abstract Factory pattern to
encapsulate the selection of a persistent store and to ensure that the
persister objects that are used are all for the correct persistent store.
-
Cache Management
The Cache Management pattern, described in Volume 1, is used with the
Persistence Layer pattern to avoid unnecessary fetches from the persistent
store.
-
Cache Consistency
The Cache Consistency pattern may be used by a persistence layer to
implement guarantees on how current the objects in a cache are.
-
Singleton
The Persistence Layer pattern uses the Singleton pattern to manage
instances of classes.
-
Marker Interface
The Persistence Layer pattern uses the Marker Interface pattern to
recognize objects that are instances of classes that it may persist.
-
CRUD
Organize persistence operations into Create, Retrieve, Update and Delete
operations.
Related patterns are
-
Object Identifier
Implementations of CRUD interfaces use the Object Identifier pattern
to identify objects in memory and in databases.
-
Object ID Manager
The Object ID Manager pattern is used with the CRUD pattern to generate
object IDs that will be unique across all domains that an object will be
used in or from.
-
Persistence Layer
The CRUD pattern is used by the Persistence Layer Pattern.
-
Stale Object
The Stale Object pattern is used when implementing the CRUD pattern
to ensure the consistency of updates.
SQL Code Description
The SQL Code Description pattern is used to implement the CRUD pattern
when the persistent store is a relational database.
-
Stale Object
-
SQL Code Description
-
Attribute Mapping Methods
-
Type Conversion
-
Change Manager
-
Object ID Manager
-
Transaction Manager
-
Connection Manager
-
Table Manager