Skip to content

Commit e96236f

Browse files
committed
Iterator design pattern - AFTER CODE for Face book friends project
- Provides limited control over data access
1 parent a743244 commit e96236f

2 files changed

Lines changed: 55 additions & 5 deletions

File tree

pattern/src/com/premaseem/Client.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.premaseem;
22

3-
import java.util.List;
4-
53
/*
64
@author: Aseem Jain
75
@title: Design Patterns with Java 9
@@ -12,7 +10,23 @@ public static void main (String[] args) {
1210
System.out.println("Iterator Pattern BEFORE CODE");
1311

1412
FaceBook faceBook = new FaceBook();
13+
Iterator faceBookIterator = faceBook.getIterator();
14+
15+
// Loop over
16+
// init data with first(), keep increment with next()
17+
// and check termination condition with hasNext()
18+
for(faceBookIterator.first();faceBookIterator.hasNext();faceBookIterator.next()){
19+
System.out.println(faceBookIterator.currentValue());
20+
}
21+
22+
// $$$ Lesson Learned $$$
23+
// Loose coupling no need to know or import data structure
24+
// Data cannot be compromised ;-)
25+
// Provides limited control over data access
1526

27+
28+
29+
/* OLD CODE
1630
// Data structure is exposed
1731
List<String> friendsList = faceBook.getFriendsList();
1832
@@ -36,7 +50,7 @@ public static void main (String[] args) {
3650
for (int i = 0; i < friendsList.size(); i++) {
3751
System.out.println(friendsList.get(i));
3852
}
39-
53+
*/
4054
// Lesson Learned
4155
// 1. Underlying Data structure is exposed
4256
// 2. Data can be manipulated

pattern/src/com/premaseem/FaceBook.java

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.ArrayList;
44
import java.util.List;
5+
import java.util.NoSuchElementException;
56

67
/*
78
@author: Aseem Jain
@@ -20,7 +21,42 @@ public FaceBook () {
2021
friendsList.add("Super Man");
2122
}
2223

23-
public List<String> getFriendsList () {
24-
return friendsList;
24+
// public List<String> getFriendsList () {
25+
// return friendsList;
26+
// }
27+
28+
public Iterator getIterator() {
29+
return new Iterator(this);
2530
}
2631
}
32+
33+
class Iterator {
34+
private FaceBook faceBook;
35+
private java.util.Iterator iterator;
36+
private String value;
37+
38+
public Iterator(FaceBook faceBook) {
39+
this.faceBook = faceBook;
40+
}
41+
42+
public void first() {
43+
iterator = faceBook.friendsList.iterator();
44+
next();
45+
}
46+
47+
public void next() {
48+
try {
49+
value = (String)iterator.next();
50+
} catch (NoSuchElementException ex) {
51+
value = null;
52+
}
53+
}
54+
55+
public boolean hasNext() {
56+
return value != null;
57+
}
58+
59+
public String currentValue() {
60+
return value;
61+
}
62+
}

0 commit comments

Comments
 (0)