Ive done research on this pattern, and Im still not sure why it is 100% better than an alternative which I will describe shortly. I will discuss two ways to implement streams. As far as I am concerned, the decorator pattern and my approach are two sides of the same coin.
I wont describe the decorator pattern here since I will assume that people interested in this answer are already familiar with it.
The alternative is to use lists. Lists are inherently ordered, and seem to do the same thing. Lets say we have an output stream that we wrap in an encryption stream which we wrap in a zip stream.
OutputStream stream = new ZipStream(new EncryptStream(new OutputStream(outputLocation)));
stream.write(data);
The alternative to would be to create an output stream, and add a zipper and encrypter to it.
OutputStream stream = new OutputStream(outputLocation);
stream.add(new EncyrptStream());
stream.add(new ZipStream());
stream.write(data);
The code for OutputStream.write would look something like:
public void write(String data) {
for(StreamDecorator d : decorators) {
data = d.doMyThing(data);
}
//continue normal write operation
}
am I correct in saying these two approaches are two sides of the same coin? If not, where is the decorator pattern more useful than this approach?