Java Reference
In-Depth Information
Table 7-3.
Comparing Classes in the Decorator Pattern, the Drink Application, and the Output Streams
Decorator Pattern
Drink Application
Output Stream
Component
Drink
OutputStream
ConcreteComponentA
ConcreteComponentB
Rum
Vodka
Whisky
FileOutputStream
ByteArrayOutputStream
PipedOutputStream
Decorator
DrinkDecorator
FilterOutputStream
ConcreteDecoratorA
ConcreteDecoratorB
Honey
Spices
BufferedOutputStream
DataOutputStream
ObjectOutputStream
There are three important methods defined in the
abstract
superclass
OutputStream
:
write()
,
flush()
, and
close()
. The
write()
method is used to write bytes to an output stream. It has three versions that let you write one
byte or multiple bytes at a time. You used it to write data to a file in the
SimpleFileWriting
class in Listing 7-16. The
flush()
method is used to flush any buffered bytes to the data sink. The
close()
method closes the output stream.
The technique to use concrete decorators with the concrete component classes for the output stream is the same
as for the input stream classes. For example, to use the
BufferedOutputStream
decorator for better speed to write to a
file, use the following statement:
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("your output file path")
);
To write data to a
ByteArrayOutputStream
, use
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(buffer); // buffer is a byte array
ByteArrayOutputStream
provides some important methods:
reset()
,
size()
,
toString()
, and
writeTo()
.
The
reset()
method discards all bytes written to it; the
size()
method returns the number of bytes written to
the stream; the
toString()
method returns the string representation of the bytes in the stream; the
writeTo()
method writes the bytes in the stream to another output stream. For example, if you have written some bytes to a
ByteArrayOutputStream
called
baos
and want to write its content to a file represented by
FileOutputStream
named
fos
, you would use the following statement:
// All bytes written to baos is written to fos
baos.writeTo(fos);
I will not discuss any more examples of writing to an output stream in this section. You can use
SimpleFileWriting
class in Listing 7-16 as an example to use any other output stream. You can use any output
stream's concrete decorators by using them as an enclosing object for a concrete component or another concrete
decorator. I will discuss
DataOutputStream
,
ObjectOutputStream
, and
PrintStream
classes with examples in
subsequent sections.