Example of Decorator Pattern – LineNumberScanner

Create a LineNumberScanner like this

public class LineNumberScanner implements Iterator
{
Scanner sc;
int i = 1;
public LineNumberScanner(Scanner sc)
{
this.sc = sc;
}

public boolean hasNextLine() {
return sc.hasNextLine();
}

public String nextLine() {
String nextLine = sc.nextLine();
if(nextLine==null) return nextLine;
else
{
return (i++)+":"+nextLine;
}
}

@Override
public void remove() {
sc.remove();
}

@Override
public boolean hasNext() {
return sc.hasNext();
}

@Override
public String next() {
return sc.next();
}
public void close()
{
sc.close();
}
}

Use the code as follows

public static void main(String[] args) throws FileNotFoundException 
{
File file = new File("D:\\Yogesh.txt");
FileInputStream fis = new FileInputStream(file);
Scanner sc = new Scanner(fis);
LineNumberScanner lineScanner = new LineNumberScanner(sc);
while(lineScanner.hasNextLine())
{
System.out.println(lineScanner.nextLine());
}
}

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.

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