Saturday, August 24, 2013

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.

2 comments:

  1. Check this URL

    https://gist.github.com/priyajava/4d73fd465f0d62860328

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete