Java Reference
In-Depth Information
Figure 6.5 shows
MyContainer
. In the revised
MyContainer
, the
iterator
method returns a reference to an
Iterator
object; the actual type turns out to
be a
MyContainerIterator
. Since
MyContainerIterator
IS-A
Iterator
, this is safe
to do.
Because
iterator
creates and returns a new
Iterator
object, whose actual
type is unknown, it is commonly known as a
factory method
. The iterator
interface, which serves simply to establish the protocol by which all sub-
classes of
Iterator
can be accessed, is shown in Figure 6.6. There are only
two changes to the implementation of
MyContainerIterator
, shown in
Figure 6.7 and both changes are at line 5. First, the
implements
clause has been
added. Second,
MyContainerIterator
no longer needs to be a public class.
A
factory method
creates a new
concrete instance
but returns it using
a reference to the
interface type.
Figure 6.8 demonstrates how the inheritance-based iterators are used. At
line 9, we see the declaration of
itr
: It is now a reference to an
Iterator
.
Nowhere in
main
is there any mention of the actual
MyContainerIterator
type.
The fact that a
MyContainerIterator
exists is not used by any clients of the
MyContainer
class. This is a very slick design and illustrates nicely the idea of
hiding an implementation and
programming to an interface
. The implementa-
tion can be made even slicker by use of nested classes, and a Java feature
known as
inner classes
. Those implementation details are deferred until
Chapter 15.
Nowhere in
main
is
there any mention
of the actual itera-
tor type.
1
package weiss.ds;
2
3
public class MyContainer
4
{
5
Object [ ] items;
6
int size;
7
8
public Iterator iterator( )
9
{ return new MyContainerIterator( this ); }
10
11
// Other methods not shown.
12
}
figure 6.5
The
MyContainer
class,
design 2
1
package weiss.ds;
2
3
public interface Iterator
4
{
5
boolean hasNext( );
6
Object next( );
7
}
figure 6.6
The
Iterator
interface, design 2
Search WWH ::
Custom Search