跳至主要内容

博文

目前显示的是 七月, 2015的博文

Patterns Learned Fom `Iterator`

Pattern one: When it comes to iterators, we can easily come up with that its use in abstracting the container and simplify the iteration operation like following example shows: Iterator it = container . iterator () while ( it . hasNext ()) { a = it . next (); // do something } No matter which kind of container you are using (the container has to be iterable and as far as I know, the commonly-used container are all iterable.), you can re-use this piece of code without any change. And this may be extract as a method, like following: public void doIterate ( Iterator it ) { while ( it . hasNext ()) { a = it . next (); // do something } } You can even make it more general with another parameter: public void doIterate ( Iterator it , Function f ) { while ( it . hasNext ()) { a = it . next (); f ( a ); } } This kind of design pattern can isolate the module of handling elements in container, whic