I have recently tried programming various versions of Iterator and Observer Patterns in Java, but currently I'm stuck at the implementation of both in one project:
What I'm trying to accomplish is to iterator through an ArrayList, which contains elements of type and after each iteration-process to inform the Observer about the change and the containing element.
I have a package with my finished Iteration-Classes, which you can see here: LONG CODE: Main Method:
package iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorMain<E> {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
// adding elements to the list
list.add("hello");
list.add("there");
/**
* Creating Iterator Object by using the list method "iterator()"
* creating it in the Iterator class
*/
Iterator<String> iterator = new IteratorStandardFilter<String>( list.iterator(), list);
IteratorStandardFilter<String> ic = new IteratorStandardFilter<String>(iterator, list);
// printing out all iterations of the list
while (ic.hasNext()) {
System.out.println(ic.next() + " ");
}
}
}
Filter Class for implementation of the various filter types:
package iterator;
import java.util.Iterator;
public abstract class IteratorFilterClass<E> implements Iterator<E> {
protected Iterator<E> standard;
public IteratorFilterClass(Iterator <E> standard){
this.standard = standard;
}
}
And last, but not least, one example of a standard iterator filter with an Exception ( guess this class is not needed) :
package iterator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class IteratorStandardFilter<E> extends IteratorFilterClass<E>{
private Iterator<E> iterator;
private List<E> list;
private int index;
public IteratorStandardFilter(Iterator<E> iterator, List<E> list) {
super(iterator);
this.iterator = iterator;
this.list = list;
index = 0;
}
@Override
public boolean hasNext() {
if ((list.size() == index))
return false;
return true;
}
@Override
public E next() throws NoSuchElementException {
E result = iterator.next();
index++;
return result;
}
}
Now i don't know how to implement the Observer Pattern in there, that's why I assumed it would be easier to write classes like
abstract class subject
class concreteSubject extends Subject
interface Observer
class ConcreteObserver implements Observer
I think i really need to practice the Observer Pattern, so implementing the Iterator into that scheme would be nice.
Any tips on where to start and how to implement it are greatly appreciated.
Thank you for your attention.
Aucun commentaire:
Enregistrer un commentaire