{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

20090323-LinkedList-III

20090323-LinkedList-III - (Java5 version with generics&...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
How about extensibility? Enter the Visitor pattern A visitor is an object which encapsulates an algorithm A visitor for the LRS defines what to do in each of the states: emptyCase nonEmptyCase
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Visitor interface to LRS the execute method is also generic (I=input,O=output): public <I,O> O execute(IAlgo<I,E,O> algo, I arg) the first parameter, alg , is the visitor (the algorithm) the second parameter, arg , is optional input to the algorithm the return type of the method is of type O
Background image of page 2
execute definition in states Empty state: public <I, O> O execute(IAlgo<I, E, O> algo, LRStruct<E> host, I arg) { return algo.emptyCase(host, arg); } NonEmpty state: public <I, O> O execute(IAlgo<I, E, O> algo, LRStruct<E> host, I arg) { return algo.nonEmptyCase(host, arg); }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Designing a visitor (IAlgo) A visitor to solve a given problem must provide the answer in each of two cases: the empty case the non-empty case One example: finding the length of a list.
Background image of page 4
Length visitor (Java5 version: with generics & autoboxing)
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Background image of page 6
Background image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (Java5 version: with generics & autoboxing) • in the empty case the answer is zero • in the non-empty case the answer is one more than the length of the rest of the list public Integer emptyCase(LRStruct<E> host, Object _){ return 0; } public Integer nonEmptyCase(LRStruct<E> host, Object _){ return 1 + host.getRest().execute(this,_); } Another visitor • How about a visitor for a list of Strings, which doubles each String • Ex: – starting list: (Fred Wilma Pebbles) – resulting list: (FredFred WilmaWilma PebblesPebbles) StringDouble visitor • in the empty case there is nothing to do • in the non-empty case the thing to do is to get the first, concatenate it to itself, and set the first to this new value public Object emptyCase(LRStruct<String> host, Object _){ return null; } public Object nonEmptyCase(LRStruct<String> host, Object _){ String s = host.getFirst(); host.setFirst(s+s); return host.getRest().execute(this,_); }...
View Full Document

{[ snackBarMessage ]}