Java Reference
In-Depth Information
}
}
Example 8-11. Using the zip algorithm to compress data
public
public class
class
ZipCompressionStrategy
ZipCompressionStrategy
implements
implements
CompressionStrategy
{
@Override
public
public
OutputStream
compress
(
OutputStream data
)
throws
throws
IOException
{
return
return new
new
ZipOutputStream
(
data
);
}
}
Now we can implement our
Compressor
class, which is the
context
in which we use our
strategy. This has a
compress
method on it that takes input and output files and writes a
compressed version of the input file to the output file. It takes the
CompressionStrategy
as
a constructor parameter that its calling code can use to make a runtime choice as to which
compression strategy to useāfor example, getting user input that would make the decision
(see
Example 8-12
)
.
Example 8-12. Our compressor is provided with a compression strategy at construction time
public
public class
class
Compressor
Compressor
{
private
private final
final
CompressionStrategy strategy
;
public
public
Compressor
(
CompressionStrategy strategy
) {
this
this
.
strategy
=
strategy
;
}
public
public
void
void
compress
(
Path inFile
,
File outFile
)
throws
throws
IOException
{
try
try
(
OutputStream outStream
=
new
new
FileOutputStream
(
outFile
)) {
Files
.
copy
(
inFile
,
strategy
.
compress
(
outStream
));
}
}
}
If we have a traditional implementation of the strategy pattern, then we can write client code
Example 8-13. Instantiating the Compressor using concrete strategy classes
Compressor gzipCompressor
=
new
new
Compressor
(
new
new
GzipCompressionStrategy
());
gzipCompressor
.
compress
(
inFile
,
outFile
);