Java Reference
In-Depth Information
A design pattern
describes a prob-
lem that occurs
over and over in
software engineer-
ing, and then
describes the solu-
tion in a suffi-
ciently generic
manner as to be
applicable in a wide
variety of contexts.
software engineering community. Writing a pattern is much like writing a
recipe for a cookbook; many common patterns have been written and,
rather than expending energy reinventing the wheel, these patterns can be
used to write better programs. Thus a design pattern describes a problem
that occurs over and over in software engineering, and then describes the
solution in a sufficiently generic manner as to be applicable in a wide vari-
ety of contexts.
Throughout the text we will discuss several problems that often arise in a
design, and a typical solution that is employed to solve the problem. We start
with the following simple problem.
In most languages, a function can return only a single object. What do we
do if we need to return two or more things? The easiest way to do this is to
combine the objects into a single object using either an array or a class. The
most common situation in which multiple objects need to be returned is the
case of two objects. So a common design pattern is to return the two objects
as a pair . This is the composite pattern .
A common design
pattern is to return
two objects as a
pair .
In addition to the situation described above, pairs are useful for imple-
menting maps and dictionaries. In both of these abstractions, we maintain
key-value pairs: The pairs are added into the map or dictionary, and then
we search for a key, returning its value. One common way to implement a
map is to use a set. In a set, we have a collection of items, and search for a
match. If the items are pairs, and the match criterion is based exclusively
on the key component of the pair, then it is easy to write a class that con-
structs a map on the basis of a set. We will see this idea explored in more
detail in Chapter 19.
Pairs are useful for
implementing key-
value pairs in maps
and dictionaries.
summary
This chapter described the Java class and package constructs. The class is the
Java mechanism that is used to create new reference types; the package is
used to group related classes. For each class, we can
Define the construction of objects
n
Provide for information hiding and atomicity
n
Define methods to manipulate the objects
n
The class consists of two parts: the specification and the implementation.
The specification tells the user of the class what the class does; the implemen-
tation does it. The implementation frequently contains proprietary code and in
some cases is distributed only as a .class file. The specification, however, is
 
Search WWH ::




Custom Search