Samuel
Samuel

Reputation: 23

Design Pattern in java unrecognized

i had the question of what is the name of the design pattern of the code below.

FileInputStream fin = new FileInputStream("X.zip");  
BufferedInputStream bin = new BufferedInputStream(fin);
ZipInputStream zin = new ZipInputStream(bin);

can anyone help me ? thanks.

Upvotes: 1

Views: 754

Answers (1)

davidxxx
davidxxx

Reputation: 131456

It is a decorator pattern.

Each new instance created adds in a dynamic way a new behavior to an existing instance.
It is dynamic as the behavior is added at runtime and not in the class itself.

In your example, you create a simple FileInputStream with basic features that you decorate with a BufferedInputStream that add the buffering behavior and you finish by decorating the BufferedInputStream instance with a ZipInputStream that provides compression features.

You can also write your code in this way :

ZipInputStream zip = new ZipInputStream(new BufferedInputStream(new FileInputStream("X.zip")));

Both BufferedInputStream and ZipInputStream derive from the FilterInputStream abstract class that is designed to enrich behavior of InputStream instances.
The javadoc explains it :

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. The class FilterInputStream itself simply overrides all methods of InputStream with versions that pass all requests to the contained input stream. Subclasses of FilterInputStream may further override some of these methods and may also provide additional methods and fields.

Upvotes: 7

Related Questions