Java Reference
In-Depth Information
An example algorithm we might want to encapsulate is compressing files. We'll give our
users the choice of compressing our files using either the zip algorithm or the gzip algorithm
and implement a generic Compressor class that can compress using either algorithm.
First we need to define the API for our strategy (see Figure 8-2 ), which I'll call Compres-
sionStrategy . Each of our compression algorithms will implement this interface. They
have the compress method, which takes and returns an OutputStream . The returned Out-
putStream is a compressed version of the input (see Example 8-9 ) .
Figure 8-2. The strategy pattern
Example 8-9. Defining a strategy interface for compressing data
public
public interface
interface CompressionStrategy
CompressionStrategy {
public
public OutputStream compress ( OutputStream data ) throws
throws IOException ;
}
We have two concrete implementations of this interface, one for gzip and one for ZIP, which
use the built-in Java classes to write gzip ( Example 8-10 ) and ZIP ( Example 8-11 ) files.
Example 8-10. Using the gzip algorithm to compress data
public
public class
class GzipCompressionStrategy
GzipCompressionStrategy implements
implements CompressionStrategy {
@Override
public
public OutputStream compress ( OutputStream data ) throws
throws IOException {
return
return new
new GZIPOutputStream ( data );
Search WWH ::




Custom Search