Example of Decorator Pattern – LowerCaseInputStream

Create a LowerCaseInputStream class as follows

public class LowerCaseInputStream extends FilterInputStream 
{

public LowerCaseInputStream(InputStream in) {
super(in);
}

@Override
public int read() throws IOException
{
int c = super.read();
if(c==-1)
return c;
else
return Character.toLowerCase(c);
}
@Override
public int read(byte b[], int offset, int len) throws IOException
{
int result = super.read(b, offset, len);
for (int i = offset; i < offset+result; i++)
{
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;
}

}

Use LowerCaseInputStream as follows

public static void main(String[] args) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("D:\\Yogesh.txt");
BufferedInputStream bufin = new BufferedInputStream(fis);
InputStream in = new LowerCaseInputStream(bufin);
int c;
try
{
while((c=in.read())!=-1)
{
System.out.print((char)c);
}
}
catch(Exception e)
{
e.printStackTrace();
}

}

Find it really interesting? You can read more about Decorator pattern in Head First Design Pattern book.

About Vineet Verma

Developer/Blogger/Gamer/Lazy Couch Potato...:P Need PDF Books: Knowledge Base
This entry was posted in Design Pattern. Bookmark the permalink.

2 Responses to Example of Decorator Pattern – LowerCaseInputStream

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s