Java Reference
In-Depth Information
To implement our object-oriented solution, we will decompose the problem into objects, each of which
do a tiny bit of work and delegate to another object. So we will start with a ShakespeareLineIterator that will
iterate over the lines of the texts. That will get passed to a ShakespeareAnthologyParser, which is responsible
for breaking the iterated lines into texts. Each text will get passed to a ShakespeareTextParser, which is
responsible for parsing the texts. It will have a method that will return a collection of ShakespeareText
instances. Those ShakespeareText instances will each provide their title, and a series of ShakespeareLine
instances. Each of those lines will contain a series of ShakespeareWord instances. The code for these classes
is given in Listing A-2.
Listing A-2. Object-Oriented Text Parsing
### ShakespeareLineIterator.java
import java.io.*;
import java.util.*;
import java.util.function.*;
import java.util.regex.*;
/**
* Iterates through the Shakespeare anthology, providing the lines of
* the anthology.
*/
public class ShakespeareLineIterator implements Iterator<String> {
private static final String SOURCE = "shakespeare.txt";
private static final Predicate<String> IS_WHITESPACE =
Pattern.compile("^\\s*$").asPredicate();
private static final Pattern BAD_CHARS =
Pattern.compile("\uFEFF|\\p{Cntrl}"); // BOMs and control characters
private static final Predicate<String> IS_COMMENT_START =
Pattern.compile("^<<").asPredicate();
private static final Predicate<String> IS_COMMENT_END =
Pattern.compile(">>$").asPredicate();
private final BufferedReader reader;
private volatile boolean closed = false;
private volatile String nextElement = null;
private volatile IOException exception = null;
/**
* Constructs an instance of the class which draws from the packaged
* complete works of Shakespeare text.
*
* @throws IOException If there is an exception getting access to
* the resource.
*/
public ShakespeareLineIterator() throws IOException {
InputStream inputStream =
ShakespeareLineIterator.class
.getClassLoader()
.getResourceAsStream(SOURCE);
 
Search WWH ::




Custom Search