Design Patterns Java™ Workbook

(Michael S) #1
Chapter 28. Iterator

This program prints:


Build inner shell
Inspect
Disassemble
Finish: Attach lift, insert fusing, wrap.


CHALLENGE 28.3


To support the setShowInterior() method, suppose that you add
a showInterior Boolean attribute to the ComponentIterator class. What
changes would you have to make in the CompositeIterator class so that
next() will return only leaf nodes if showInterior is false?

Thread-Safe Iterators................................................................................................................................


When it returns the next value in a collection to a client, an iterator also returns control of the
program. This opens the possibility that a client will take an action that will change the
collection over which you are iterating. Consider a program that can update a list in one
thread while another thread is iterating over the list:


package com.oozinoz.applications;
import java.util.*;
public class ShowConcurrentFor implements Runnable
{
private List list;


protected static List upMachineNames()
{
return new ArrayList
(
Arrays.asList
(
new String[]
{
"Mixer1201",
"ShellAssembler1301",
"StarPress1401",
"UnloadBuffer1501"
}
)
);
}


protected void go()
{
list = Collections.synchronizedList(
upMachineNames());
for (int i = 0; i < list.size(); i++)
{
if (i == 1)
{ // simulate wake-up
new Thread(this).start();
}

Free download pdf