Design Pattern
Say A is the producer, B is the consumer
Iterator Pattern¶
Pull pattern: B pull values from A
A implements Iterable<T>{
Iterable<T> iterator();
}
B uses Iterator methods{
boolean hasNext();
T next();
}Using iterator is easy
Implementing it is difficult
iterator should remember its position (or you don’t really know whether it hasNext)
underlying data structure can’t be mutated(what if the Next is deleted?)
need version number on every node of the data structure
If the version number is changed, it will throw
ConcurrentMod(ification)Exception
Used when you have different data type of sources to be pulled from, so you don’t want to pull directly the hashTable or arrayList they use to iterate those values. You want something more generic. Here comes the iterator. Java has its own iterator method. You can create iterator from ArrayList or hashTable.
Observer Pattern¶
Push Pattern: A pushes values to B
interface Observer<T>{
void notify(T elem);
}
interface Obeservable<T>{
void register Observer(Observer<T> obs);
}
Streams¶
“pull” with transformers
List<T> l;
l.stream(); //read in a strem of T
l.filter(predicate); //filter out all predicates in T
l.map(function); //get a Stream<Integer> if function: Function<T,Integer>When you want to pull something
findFirst returns Optimal<T>
Optional<T> of(T)//converts T to Optional <T>
Optional<T> ofNullible(T) // if T is empty, it returns an empty Optional<T>