1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package jp.liq.container.util;
17
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21
22
23
24
25
26
27
28
29 public abstract class AbstractFinder<T, S extends AbstractFinder<T, S>>
30 implements Iterable<T> {
31 private final List<Matcher<T>> matchers;
32
33
34
35
36 public AbstractFinder() {
37 this.matchers = new ArrayList<Matcher<T>>();
38 }
39
40 protected void addMatcher(Matcher<T> matcher) {
41 matchers.add(matcher);
42 }
43
44
45
46
47 protected abstract S getThis();
48
49 protected abstract Iterator<T> getCandidates();
50
51 public Iterator<T> iterator() {
52 return new MatchingIterator();
53 }
54
55 private class MatchingIterator implements Iterator<T> {
56 private final Iterator<T> candidates;
57 private T nextMatches;
58
59 MatchingIterator() {
60 candidates = getCandidates();
61 findNext();
62 }
63
64 public void findNext() {
65 while(candidates.hasNext()) {
66 T next = candidates.next();
67 if(matches(next)) {
68 nextMatches = next;
69 return;
70 }
71 }
72 nextMatches = null;
73 }
74
75 public boolean hasNext() {
76 return nextMatches != null;
77 }
78
79 public T next() {
80 T rv = nextMatches;
81 findNext();
82 return rv;
83 }
84
85 private boolean matches(T candidate) {
86 for(Matcher<T> matcher: matchers) {
87 if(matcher.matches(candidate)) {
88 continue;
89 } else {
90 return false;
91 }
92 }
93 return true;
94 }
95
96 public void remove() {
97 throw new UnsupportedOperationException();
98
99 }
100 }
101
102 }