Design Patterns Java™ Workbook

(Michael S) #1
Chapter 27. Decorator

DECORATOR classes typically implement their operations by relying on the decorator object
they receive in their constructors. For example, the GZIPOutputStream class implements
its write() operations by compressing the bytes it receives and then writing them to the
OutputStream object that its constructor requires. In other words, the
GZIPOutputStream class adds the behavior of compression to the OutputStream object
it receives. This is typical of the intent of DECORATOR.


Requiring an OutputStream object in each OutputStream constructor is a recursive idea.
Like COMPOSITE, the DECORATOR pattern requires some classes in a hierarchy to act as leaf
nodes. For example, you can instantiate the FileOutputStream class without already
having an OutputStream object.


Most of Java's stream classes are part of the java.io package, but the
DeflaterOutputStream, GZIPOutputStream, and ZipOutputStream classes that
Figure 27.1 shows are part of the package java.util.zip. The ZipOutputStream class
lets you create a compressed file with multiple entries, whereas the GZIPOutputStream
class compresses a single input file. Which of these classes you choose depends on how you
want to "decorate" the output. For example, you can wrap a GZIPOutputStream object
around a FileOutputStream object to create a zipped version of an existing file:


package com.oozinoz.applications;
import java.io.;
import java.util.zip.
;
public class ShowGzip
{
public static void main(String args[])
throws IOException
{


String fileName = "demo.doc";
java.net.URL url =
ClassLoader.getSystemResource(fileName);
InputStream in = url.openStream();


GZIPOutputStream out =
new GZIPOutputStream(
new FileOutputStream(
url.getFile() + ".gz"));


byte[] data = new byte[100];
while (true)
{
int n = in.read(data);
if (n == -1)
{
break;
}
out.write(data, 0, n);
}
out.close();
in.close();
}
}

Free download pdf